Raees Khan Raees Khan - 3 months ago 9
C Question

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

}

Answer

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
    }


}