简体   繁体   English

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

[英]using gdb to check sprintf() function step by step

I have a program in C as followings: 我在C中有一个程序,如下所示:

char str[50] = {0};
int a = 15;
sprintf(str, "%d", a);
printf("%s\n", str);

It can get the correct result -- 15. But if I use gdb to check the sprintf() function step by step, "sprintf.c: No such file or directory." 它可以得到正确的结果-15。但是,如果我使用gdb逐步检查sprintf()函数,则“ sprintf.c:没有这样的文件或目录”。 is shown and then it is killed. 被显示,然后被杀死。 Why that happens? 为什么会这样? Actually, I used the sprintf() function in another project and now it occurs overlap. 实际上,我在另一个项目中使用了sprintf()函数,现在它发生了重叠。 I doubt if there any dangers to use the sprintf() function? 我怀疑使用sprintf()函数是否存在危险? How can I avoid it? 我该如何避免呢?

Thanks in advance! 提前致谢!

You can use sprintf (but beware, it is unsafe so obsolete, and you should use snprintf , eg snprintf(str, sizeof(str), "%d", a); in your case). 您可以使用sprintf (但要注意,它不安全,因此已过时, 使用snprintf ,例如您的情况下的snprintf(str, sizeof(str), "%d", a); )。

It is just that, because your libc was not compiled with debug information, you cannot step inside the execution of sprintf (except by stepping on individual machine instructions). 仅仅是因为您的libc并未使用调试信息进行编译,所以您无法进入 sprintf的执行(除非进入单个机器指令)。

The danger of sprintf is well known, it can make a buffer overflow . sprintf的危险众所周知,它会使缓冲区溢出 This is why you should not use it and use snprintf instead (or, if your platform has it and you want a dynamically allocated string, asprintf(3) which is available on most Linux systems). 这就是为什么您不应该使用它,而改用snprintf (或者,如果您的平台上有它并且您想要一个动态分配的字符串, asprintf(3) ,在大多数Linux系统上都可以使用)。

BTW the Linux man page sprintf(3) explicitly says: 顺便说一句,Linux手册页sprintf(3)明确表示:

  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)). 

It is sometimes quite useful to take into account the result of snprintf (which is the number of bytes actually needed for the computed string, which could be larger than the given size limit enforced on the result). 有时考虑snprintf的结果(这是计算出的字符串实际需要的字节数,可能会大于对结果施加的给定大小限制),这非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM