realloc and Segmentation Fault

Vladimir Vassilev vladimir@logicom-bg.com
Wed Jul 19 16:39:00 GMT 2006


Hello Jonathan,

There is bug in your program. The 'valid' pointer in 'main' has the same 
value before and after the call to function1. The realloc call in 
function1 deallocates this memory allocates new one and returns the new 
address. However in main you continue to use the now invalid address and 
use it in the next call.

Probably you assume realloc just extends the already allocated memory 
and the ptr remains the same which is not the case.

Regards,
Vladimir

Jonathan Shan wrote:
> Hello all,
>
> The goal of my program is to create a dynamic array of a struct type. 
> The struct type has two strings inside it. From time to time I want to 
> copy strings into the strings in the dynamic array. Then increase the 
> size of the dynamic array. I have narrowed the problem down to the 
> realloc function but I still don't know why it says segmentation fault 
> or hangs (sometimes).
>
> Here is the simplified code which exhibits the problem:
>
> /*libraries here */
>
> #define SIZEOF_BUCKETSTRUCT 70
> #define SIZEOF_HOSTNAME 20
> #define SIZEOF_DESCRIPTION 50
>
> int bucketsize = 1;
> struct bucket
> {
>     char *hostname;
>     char *description;
> };
> void function1(struct bucket *valid)
> {
>     valid[bucketsize - 1].hostname = malloc (sizeof(char) * 20);
>     strncpy(valid[bucketsize - 1].hostname, "test hostname", 20);
>     valid[bucketsize - 1].hostname[19] = '\0';
>     printf("hostname is %s \n", valid[bucketsize - 1].hostname);
>
>     valid[bucketsize - 1].description = malloc (sizeof(char) * 50);
>     strncpy(valid[bucketsize - 1].description, "test buf", 50);
>     valid[bucketsize - 1].description[49] = '\0';
>     printf("description is %s \n", valid[bucketsize - 1].description);
> /* problem is here */
>     valid = (struct bucket *) realloc (valid, 70 * ((bucketsize) + 1));
>     bucketsize++;
> }
> int main()
> {
>   struct bucket *valid;
>   valid = (struct bucket *) malloc (SIZEOF_BUCKETSTRUCT);
>   if (valid == NULL)
>   {
>     printf("error in allocating memory \n");
>     exit(1);
>   }
>
>   function1(valid);
>   function1(valid);
>
>   return 0;
> }
>
> Thank you,
>
> Jonathan Shan


-- 
=========================================================================================
Vladimir Vassilev                      |
Logicom Consult EOOD                   | E-mail:
Mladost 1A, bl. 501, apt. 68           | vladimir@logicom-bg.com
Sofia, Bulgaria                        | Web:
Tel:+359 886979158                     | http://www.logicom-bg.com




More information about the Gcc-help mailing list