strcpy 导致线程 1:信号 SIGABRT [英] strcpy causing Thread 1: signal SIGABRT

查看:60
本文介绍了strcpy 导致线程 1:信号 SIGABRT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在做一些练习代码,但我无法弄清楚这个顽固的线程1:

I'm just doing some practice code but I can't figure out this stubborn Thread 1:

信号 SIGABRT 错误.

signal SIGABRT error.

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;
}

推荐答案

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

You need to allocate more memory to solve this; you cannot store 9 bytes in 6 bytes space — that causes an error.

#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;
}

这篇关于strcpy 导致线程 1:信号 SIGABRT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆