简体   繁体   中英

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. 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.

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 . You need to allocate enough memory to store all 3 animal names (13 = 3 times the longest animal name, goat + 1 null character). Also, use calloc to zero out the string.

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. Use int main() instead.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM