【问题标题】:strcpy causing Thread 1: signal SIGABRTstrcpy 导致线程 1:信号 SIGABRT
【发布时间】:2017-12-19 03:37:32
【问题描述】:

我只是在做一些练习代码,但我无法弄清楚这个顽固的线程 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;
}

【问题讨论】:

  • 您正在尝试使用strcpy 将 9 个字符(包括空终止符)复制到只能容纳 6 个字符的空间中。

标签: c xcode multithreading


【解决方案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;
}

【讨论】:

    【解决方案2】:

    你需要分配更多的内存来解决这个问题;你不能在 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      相关资源
      最近更新 更多