简体   繁体   English

打印几行后C程序崩溃

[英]C program crashes after printing few lines

I have written this piece of code in C, but when I run it, the program crashes after printing few lines. 我已经用C语言编写了这段代码,但是当我运行它时,该程序在打印几行后便崩溃了。 Please solve the problem. 请解决问题。

code: 码:

#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);
    }

}

Your program crashed because sentence didn't have enough memory allocated to store the string. 您的程序崩溃是因为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("");

You're only allocating 1 char for sentence . 您只为sentence分配1个char You need to allocate enough memory to store all 3 animal names (13 = 3 times the longest animal name, goat + 1 null character). 您需要分配足够的内存来存储所有3种动物名称(13 =最长动物名称的3倍,山羊+ 1个空字符)。 Also, use calloc to zero out the string. 另外,使用calloc将字符串清零。

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

Also, you're not freeing your memory when you are done: 此外,完成操作后不会释放内存:

free(sentence);

By the way, you should not use void main() as it is not standards compliant. 顺便说一句,您不应该使用void main()因为它不符合标准。 Use int main() instead. 使用int main()代替。

In this case it's a bad idea to allocate and free memory in the loop. 在这种情况下,在循环中分配和释放内存是个坏主意。 It's harmless, but it's much better to reuse allocated memory in this case. 这是无害的,但是在这种情况下,重用分配的内存要好得多。

You also don't have to use malloc and free, and can instead declare a char array of a fixed length. 您也不必使用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