strcpy导致线程1:信号SIGABRT

问题描述 投票:-1回答:2

我只是在做一些练习代码,但我无法弄清楚这个顽固的线程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;
}
c xcode multithreading
2个回答
1
投票

strlen(“whatever”)> 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
投票

你需要分配更多的内存来解决这个问题;你不能在6字节空间中存储9个字节 - 这会导致错误。

Solution

#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.