[英]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.