簡體   English   中英

打印幾行后C程序崩潰

[英]C program crashes after printing few lines

我已經用C語言編寫了這段代碼,但是當我運行它時,該程序在打印幾行后便崩潰了。 請解決問題。

碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>


void main() {

    char *str[] = {"Dog", "Cat", "Hen", "Goat"};
    char *sentence;
    int i;
    srand(time(NULL));

    for(i=0; i<20; i++) {
        sentence = strdup("");
        strcat(sentence, str[rand()%4]);
        strcat(sentence, str[rand()%4]);
        strcat(sentence, str[rand()%4]);
        printf("%s\n", sentence);
    }

}

您的程序崩潰是因為sentence沒有分配足夠的內存來存儲字符串。

void main() {

    char *str[] = {"Dog", "Cat", "Hen", "Goat"};
    char *sentence = NULL; //initialize the string
    int i;
    srand(time(NULL));

    for(i=0; i<20; i++) {
        sentence=malloc(13); // longest string would be GoatGoatGoat + terminating null
        sentence[0]='\0';
        strcat(sentence, str[rand()%4]);
        strcat(sentence, str[rand()%4]);
        strcat(sentence, str[rand()%4]);
        printf("%s\n", sentence);
        free(sentence); //always free the allocated memory
    }


}
sentence = strdup("");

您只為sentence分配1個char 您需要分配足夠的內存來存儲所有3種動物名稱(13 =最長動物名稱的3倍,山羊+ 1個空字符)。 另外,使用calloc將字符串清零。

sentence = calloc(13, sizeof(char));  /* CORRECT */

此外,完成操作后不會釋放內存:

free(sentence);

順便說一句,您不應該使用void main()因為它不符合標准。 使用int main()代替。

在這種情況下,在循環中分配和釋放內存是個壞主意。 這是無害的,但是在這種情況下,重用分配的內存要好得多。

您也不必使用malloc和free,而可以聲明一個固定長度的char數組。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main()
{
    char *str[] = {"Dog", "Cat", "Hen", "Goat"};
    char sentence[64];
    int i;

    srand(time(NULL));

    for(i = 0; i < 20; i++)
    {
        strcpy(sentence, str[rand() % 4]);
        strcat(sentence, str[rand() % 4]);
        strcat(sentence, str[rand() % 4]);
        printf("%s\n", sentence);
    }
    return 0;
}

暫無
暫無

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

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