簡體   English   中英

sprintf()程序未定義的返回值

[英]sprintf() program undefined return value

#include <stdio.h>
#include <stdlib.h>
//#include <wchar.h>

int main(int argc, char **argv)
{
     char *c = (char *)malloc(sizeof(char) * 30);

     if (argc < 2)
     {      
         fprintf(stderr, "%s", "argc < 2\n");
         exit(1);
     }

     sprintf(c, "sprintf() string : %s\t argc: %i", argv[1], argc);
     fprintf(stdout, "%s\n", c);
     fprintf(stdout, "%s", "Done!\n");
     free(c);

     return 0;
}

我已經在兩個編譯器上編譯了該程序,並且都產生相同的運行時錯誤。 但是我無法確定該錯誤。 我是否在sprintf()中正確格式化了字符串? 有什么我忘了解釋的嗎?

我使用argv [1] =“ Sunday”的參數運行該程序

您正在malloc處將c設置為30字節大小。

然后在sprintf中寫入28個字節,外加argv [1]字符串和argc作為字符串。 這幾乎肯定會超過30個字節。

您需要正確計算需要為c進行malloc的實際大小。 或者,您應該使用snprintf而不是sprintf,可以將其限制為寫入30個字符並避免崩潰。

您在c打印了超過30字符。 要在發生這種情況時切斷輸出,而不是崩潰,請執行以下操作:

snprintf(c, 30, "bla bla....

暫無
暫無

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

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