打印几行后C程序崩溃

时间:2016-08-17 14:15:21

标签: c

我用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);
    }

}

3 个答案:

答案 0 :(得分:2)

您的程序崩溃是因为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
    }


}

答案 1 :(得分:1)

sentence = strdup("");

您只为char分配了1 sentence。您需要分配足够的内存来存储所有3个动物名称(13 =最长动物名称的3倍,山羊+ 1个空名称)。另外,使用calloc将字符串清零。

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

此外,完成后你不会释放你的记忆:

free(sentence);

顺便说一句,您不应该使用void main(),因为它不符合标准。请改用int main()

答案 2 :(得分:0)

在这种情况下,在循环中分配和释放内存是个坏主意。它是无害的,但在这种情况下重用已分配的内存要好得多。

你也不必使用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;
}
相关问题