Reputation: 1600
I am getting a segmentation fault when i try to concatenate two strings as shown in the code below:
EDITED
//global variables
char *result="hi";
char *temp;
size_t write_data(char *ptr, size_t size, size_t nmeb, void *stream)
{
temp=(char *)ptr;
while(*result)++result;
while(*result++ = *temp++);
return fwrite(ptr,size,nmeb,stream);
}
What am i doing wrong here?
Thanks
Upvotes: 0
Views: 207
Reputation: 33667
You are storing values into the address pointed to by result
without having initialized result
to point to ENOUGH memory that you can use to store the result. By initializing result to "Hi" you have allocated three bytes for it. This is not enough to hold the additional data that you are attempting to append at the end.
Upvotes: 2
Reputation: 34625
while(*result)++result; // 1
while(*result++ = *temp++); // 2
By the end of line 1, result reaches its end, and at line 2, you are passing result
end and dereferencing it.
char *result="hi";
result
is pointing to the string literal hi
with null terminated. Locations after the null termination aren't valid accessible locations for result
to access. But you are trying to access them at line 2.
Upvotes: 1