C 使用gdb逐步检查sprintf()函数

C 使用gdb逐步检查sprintf()函数,c,printf,overlap,C,Printf,Overlap,我的C语言课程如下: char str[50] = {0}; int a = 15; sprintf(str, "%d", a); printf("%s\n", str); 它可以得到正确的结果——15。但是如果我使用gdb一步一步地检查sprintf()函数,就会显示“sprintf.c:没有这样的文件或目录”,然后将其终止。为什么会这样?实际上,我在另一个项目中使用了sprintf()函数,现在它发生了重叠。我怀疑使用sprintf()函数是否有危险?我怎样才能避免呢 提前谢谢 您可以使用

我的C语言课程如下:

char str[50] = {0};
int a = 15;
sprintf(str, "%d", a);
printf("%s\n", str);
它可以得到正确的结果——15。但是如果我使用gdb一步一步地检查sprintf()函数,就会显示“sprintf.c:没有这样的文件或目录”,然后将其终止。为什么会这样?实际上,我在另一个项目中使用了sprintf()函数,现在它发生了重叠。我怀疑使用sprintf()函数是否有危险?我怎样才能避免呢


提前谢谢

您可以使用
sprintf
(但要注意,它太过时了,不安全,您应该使用,例如
snprintf(str,sizeof(str),“%d”,a);

只是,因为您的libc没有使用调试信息编译,所以您不能在
sprintf
的执行过程中单步执行(单步执行单独的机器指令除外)

sprintf的危险是众所周知的,它可能会造成严重后果。这就是为什么您不应该使用它,而应该使用
snprintf
(或者,如果您的平台有它,并且您希望动态分配字符串,这在大多数Linux系统上都可用)

顺便说一句,Linux手册页明确指出:

有时考虑
snprintf
的结果非常有用(这是计算字符串实际需要的字节数,可能大于对结果强制执行的给定大小限制)

   Because sprintf() and vsprintf() assume an arbitrarily long string,
   callers must be careful not to overflow the actual space; this is
   often impossible to assure.  Note that the length of the strings
   produced is locale-dependent and difficult to predict.  Use
   snprintf() and vsnprintf() instead (or asprintf(3) and vasprintf(3)).