strcpy pass initialized null pointer c [duplicate]

江枫思渺然 提交于 2019-12-12 19:13:25

问题


I'm trying out the following code:

int main()
{
   char *yo = "yo";
   char *whaddup = NULL;
   strcpy(whaddup,yo);
}

and I get a segfault. Complete C noob here - other places say I should initialize whaddup as an array. Why can't I pass in a pointer to null?


回答1:


Just any strcpy documentation will tell you that the destination string should be a char array large enough to hold the string and the NUL terminator.

So what you need is something like

char* yo = "yo";
char* whaddup = malloc(strlen(yo)+1);
strcpy(whaddup, yo);

Or alternatively you could use strdup function which does this for you, but it's not standard as it's POSIX only.




回答2:


You have to either declare whaddup as a character array or ideally allocate space for it with malloc.

int main()
{
   char *yo = "yo";
   char *whaddup = malloc(sizeof(char) * 8); // buffer for 8 characters
   strcpy(whaddup,yo);
}

By initializing whaddup to NULL you are not giving it any space in memory, so even copying one character into it will result in a segmentation fault.




回答3:


You can pass in a pointer to null, but you can not copy string from pointer to null.

The function char* strcpy(char* dest, const char* src) is copy string from address src to address dest, your dest is null.



来源:https://stackoverflow.com/questions/38065778/strcpy-pass-initialized-null-pointer-c

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