我只是在做一些练习代码,但我无法弄清楚这个顽固的主题1:
发出SIGABRT错误信号。
int main(){
char diet[] = "vegan";
printf("Because of health concerns, my diet is now %s.\n", diet);
strcpy(diet, "whatever");
printf("Before the health concerns, my diet was %s.\n", diet);
return 0;
}
答案 0 :(得分:1)
strlen(“不管”)> strlen(“vegan”)=未定义的行为。
为什么你认为你需要复制字符串。你可以这么做:
int main(){
char *diet = "vegan";
printf("Because of health concerns, my diet is now %s.\n", diet);
diet = "whatever";
printf("Before the health concerns, my diet was %s.\n", diet);
return 0;
}
答案 1 :(得分:1)
你需要分配更多的内存来解决这个问题;你不能在6个字节的空间中存储9个字节 - 这会导致错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *create(const char *src) {
char *ret = calloc(sizeof(char*) , strlen(src) + 1);
strcpy(ret , src);
return ret;
}
int main(){
char *diet = create("Vegan");
printf("Because of health concerns, my diet is now %s.\n", diet);
free(diet); // always free it after using it or before changing it
diet = create("whatever");
printf("Before the health concerns, my diet was %s.\n", diet);
free(diet);
return 0;
}