C strcpy = Unhandled exception: Access violation writing location 0x00000000

久未见 提交于 2019-12-02 04:43:13

问题


I have a problem with strcpy function. Using C. Main point of this simple code (below) is copying a string from a array to the array of pointers.

char string[20] = "ABCDEFGH\0";
char * array_of_pointers[20];

// now I want to copy string to the first available slot;

strcpy(array_of_pointers[0],string);

Then strcpy throws me error:

Unhandled exception: Access violation writing location 0x00000000.

Why? I know that this problem is probably simple, but I really don't have a clue.


回答1:


The target buffer has not been initialized. array_of_pointers[0] is just a pointer that (in this case based on the error information from the access violation) points to address 0. You need to initialize it. Possibly:

array_of_pointers[0] = malloc( strlen( string ) + 1 );

array_of_pointers is an array of 20 pointers. Defined like that, each entry in that array must be initialized before it can be used. Remember too that if you do use malloc (or possibly strdup) to allocate the memory, use free to release the memory.




回答2:


You need to initialize array_of_pointers :

array_of_pointers[0] = malloc(strlen(string)+1);

Or best:

array_of_pointers[0] = strdup(string);


来源:https://stackoverflow.com/questions/13778918/c-strcpy-unhandled-exception-access-violation-writing-location-0x00000000

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