segmentation fault with strcpy [duplicate]

我的梦境 提交于 2019-11-29 02:49:00

问题


I am wondering why am I getting segmentation fault in the below code.

int main(void)
{
        char str[100]="My name is Vutukuri";
        char *str_old,*str_new;

        str_old=str;
        strcpy(str_new,str_old);

        puts(str_new);

        return 0;
}

回答1:


You haven't initialized *str_new so it is just copying str_old to some random address. You need to do either this:

char str_new[100];

or

char * str = (char *) malloc(100);

You will have to #include <stdlib.h> if you haven't already when using the malloc function.




回答2:


str_new is an uninitialized pointer, so you are trying to write to a (quasi)random address.




回答3:


Because str_new doesn't point to valid memory -- it is uninitialized, contains garbage, and likely points into memory that's not even mapped if you're getting a segmentation error. You have to make str_new point to a valid block of memory large enough to hold the string of interest -- including the \0 byte at the end -- before calling strcpy().



来源:https://stackoverflow.com/questions/10326586/segmentation-fault-with-strcpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!