0

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

CuriousCoder
  • 1,582
  • 5
  • 28
  • 55
  • 2
    Um... where's `result` initialized? – Mysticial Nov 02 '11 at 03:10
  • Initializing result to "hi" or "\0" give me segmentation fault. – CuriousCoder Nov 02 '11 at 03:12
  • Refer K&R book on how to write strcat(). That should give you a very good idea on what's going wrong in your program. – yasouser Nov 02 '11 at 03:24
  • What exactly are you trying to do? Are you trying to add some sort of string in front of `ptr` and then `fwrite` that? – AusCBloke Nov 02 '11 at 03:25
  • this is part of curl code. write_data() is a callback function that will be called every time a data chunk is obtained from a web server. what i am trying to do is concatenate each chunk of data together and will finally will send the full data back to the client. – CuriousCoder Nov 02 '11 at 03:31

2 Answers2

2

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.

Joel Spolsky
  • 33,372
  • 17
  • 89
  • 105
  • I have changed the code to make result initialize to some value. Still, i get segfault – CuriousCoder Nov 02 '11 at 03:21
  • thanks for the explanation. but, i do not know how much memory result will occupy. So, what should i do in this case? just allocate arbitrary large memory for it ? that is not a good practice. – CuriousCoder Nov 02 '11 at 03:23
  • 1
    The amount of memory you need is strlen(result) + strlen(ptr) + sizeof('\0') so that is how much you should allocate. – Joel Spolsky Nov 02 '11 at 03:25
  • @JoelSpolsky: sizeof('\0') is equivalent to sizeof(int) in C. In C++, however, sizeof('\0') is equivalent to sizeof(char). See [this](http://stackoverflow.com/questions/2172943/size-of-character-a-in-c-c). – Alexey Frunze Nov 02 '11 at 06:00
1
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.

Mahesh
  • 34,573
  • 20
  • 89
  • 115