I have a global structure:
struct thread_data{
char *incall[10];
int syscall arg_no;
开发者_如何学Python int client_socket;
};
and in main()
char buffer[256];
char *incall[10];
struct thread_data arg_to_thread;
strcpy(incall[0],buffer); /*works fine*/
strcpy(arg_to_thread.incall[0],buffer); /*causes segmentation fault*/
Why does this happen and Please suggest a way out.
thanks
A segfault means that something is wrong. But no segfault does not mean that something isn't wrong. If two situations are basically the same, and one segfaults and the other does not, it usually means that they are both wrong, but only one of them happens to be triggering the segfault.
Looking at the line char* incall[10]
, what that means is you have an array of 10 pointers to a char. By default, these pointers will be pointing at random places. Therefore, strcpying into incall[0] will be copying the string to a random location. This is most likely going to segfault! You need to initialise incall[0] first (using malloc
).
So a bigger question is why doesn't the first line segfault? I would imagine the reason is that it just so happens that whatever was in memory before was a valid pointer. Therefore, the strcpy doesn't segfault, it just overwrites something else which will later cause completely unexpected behaviour. So you must fix both lines of code.
Another issue (once you have fixed that) is that strcpy
itself is highly dangerous -- since it copies strings until it finds a 0 byte and then stops, you can never be sure exactly how much it's going to copy (unless you use strlen
to allocate the destination memory). So you should use strncpy
instead, to limit the number of bytes copied to the size of the buffer.
You've not initialized the pointer incall[0]
, so goodness only knows where the first strcpy()
writes to. You are unlucky that your program does not crash immediately.
You've not initialized the pointer arg_to_thread.incall[0]
, so goodness only knows where the second strcpy()
writes to. You are lucky that your program crashes now, rather than later.
In neither case is it the compiler's fault; you must always ensure you initialize your pointers.
- Make sure you have enough memory allocated for your string buffers.
- Stay away from
strcpy
. Usestrncpy
instead.strcpy
is a notorious source of buffer overflow vulnerabilities - a security and maintenance nightmare for which there really isn't an excuse.
精彩评论