[英]strcpy causing Thread 1: signal SIGABRT
I'm just doing some practice code but I can't figure out this stubborn Thread 1: 我只是在做一些练习代码,但我不知道这个顽固的线程1:
signal SIGABRT error.
信号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;
}
strlen("whatever") > strlen("vegan") = undefined behavior. strlen(“ whatever”)> strlen(“ vegan”)=未定义的行为。
Why do you think you need to copy the strings around. 为什么您认为需要复制字符串。 You could just do:
您可以这样做:
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;
}
You need to allocate more memory to solve this; 您需要分配更多的内存来解决此问题; you cannot store 9 bytes in 6 bytes space — that causes an error.
您不能在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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.