2014-08-29 73 views
1

我在C程序爲如下:用gdb檢查的sprintf()函數步步

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

它可以得到正確的結果 - 15.但是,如果我使用gdb來檢查的sprintf( )功能一步一步地「sprintf.c:沒有這樣的文件或目錄」。被顯示,然後它被殺死。爲什麼會發生?實際上,我在另一個項目中使用了sprintf()函數,現在它發生重疊。我懷疑是否有任何危險使用sprintf()函數?我怎樣才能避免它?

在此先感謝!

回答

1

您可以使用sprintf(但要注意,它是不安全的如此過時了,你應該使用snprintf,例如你的情況snprintf(str, sizeof(str), "%d", a);)。

,就是這樣,因爲你的libc沒有編譯帶有調試信息,你不能步內sprintf執行(除個別步進機說明上)。

sprintf的危險是衆所周知的,它可以使buffer overflow。這就是爲什麼你不應該使用它並使用snprintf來代替(或者,如果你的平臺擁有它並且你想要一個動態分配的字符串,在大多數Linux系統上都可以使用asprintf(3))。

BTW 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結果(這實際上是需要計算的字符串的字節數有時是相當有用的,這可能大於對結果執行的給定大小限制)。