簡體   English   中英

使用gdb逐步檢查sprintf()函數

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

我在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 ,例如您的情況下的snprintf(str, sizeof(str), "%d", a); )。

僅僅是因為您的libc並未使用調試信息進行編譯,所以您無法進入 sprintf的執行(除非進入單個機器指令)。

sprintf的危險眾所周知,它會使緩沖區溢出 這就是為什么您不應該使用它,而改用snprintf (或者,如果您的平台上有它並且您想要一個動態分配的字符串, asprintf(3) ,在大多數Linux系統上都可以使用)。

順便說一句,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)). 

有時考慮snprintf的結果(這是計算出的字符串實際需要的字節數,可能會大於對結果施加的給定大小限制),這非常有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM