sscanf 导致栈溢出的问题

#include <stdio.h>

void test()
{	
	
	unsigned short buf[6] = {0};
	
	for(int i=0;i <6;i++)
		printf("before sscanf buf[%d] = %d\n", i, buf[i]);

	sscanf("2021-06-07 17:55:05", "%d-%d-%d %d:%d:%d", &buf[0], &buf[1],&buf[2], &buf[3], &buf[4], &buf[5]);

	for(int i=0 ;i<6; i++)
		printf("after sscanf buf[%d] = %d\n", i, buf[i]);
}

int main()
{
	test();
   	return 0;
}

运行结果

root@ubuntu:~/Desktop/test# ./testCode 
before sscanf buf[0] = 0
before sscanf buf[1] = 0
before sscanf buf[2] = 0
before sscanf buf[3] = 0
before sscanf buf[4] = 0
before sscanf buf[5] = 0
after sscanf buf[0] = 2021
after sscanf buf[1] = 6
after sscanf buf[2] = 7
after sscanf buf[3] = 17
after sscanf buf[4] = 55
after sscanf buf[5] = 5
*** stack smashing detected ***: terminated
已放弃 (核心已转储)

请问为什么会导致栈溢出呢?

用 scanf_s

改成 int buf[6] = {0} 就可以了。你用%d格式化

如果非得用unsigned short buf[6]的话,那用%hd格式化

不知道你的sscanf为什么那么用,你试试这样
char buff[100];

sscanf(buff,"2021-06-07 17:55:05", "%d-%d-%d %d:%d:%d", &buf[0], &buf[1],&buf[2], &buf[3], &buf[4], &buf[5]);

 

    sscanf("2021-06-07 17:55:05", "%4d-%2d-%2d %2d:%2d:%2d",
                &buf[0], &buf[1],&buf[2], &buf[3], &buf[4], &buf[5]);

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632