Re: char ** realloc
From: Zoran Cutura (Zoran.Cutura_at_daimlerchrysler.com)
Date: 05/06/03
- Next message: Jignesh: "Re: Developing Proxy Server - Don't have enough speed"
- Previous message: nitin_panj: "Makefile utility"
- Maybe in reply to: Default User: "Re: char ** realloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] [ attachment ]
Date: Tue, 06 May 2003 12:26:02 +0200
On Tue, 29 Apr 2003 23:22:25 +0000, Joshua Jones wrote:
> I've looked at this for a while, and I just can't figure it out.
> The following code is causing my program to crash. Does anyone
> see anything wrong with this code?
>
> -------------
> char ** result;
> ...
>
> result = realloc (result, (((*count)+1) *
> sizeof (char *)));
When realloc fails, with the above you have introduced
a memory leak, as the original memory is not deleted, but all
references to it have been lost.
With realloc one should always use a temporary pointer to check
whether reallocation was successful. Even when decreasing
memory, although one might not expect realloc to fail in this
case, but there is nothing in the standard that guarantees success
in some case.
Second, if *count is the size of the original array, increasing it
by only one element may become a performance problem. realloc might
have to copy the whole original array every time you increase
the array, which most certainly costs some time. Usually people
double the size and in the end decrease the array to the actually
required size, or at least add a reasonable number of bytes to the
original size when needed.
> if (result == NULL)
> fprintf(stderr, "Realloc failed\n");
If the reallocation was not successful the following code should not
be executed. Your seg fault could stem from here.
>
> result[*count] = malloc (strlen(inet_ntoa(
> recv_iphdr->ip_src))+1);
> if (result[*count] == NULL)
> fprintf(stderr, "malloc failed\n");
>
> --------------
>
> I've verified that I'm malloc'ing the right amount of bytes, that
> inet_ntoa() is returning valid data, and everything. I think that
> the problem is with this code because when I declare result as:
>
> char result[40][40];
>
> then I get no seg fault. Does anyone have any clues?
-- Z (Zoran.Cutura@daimlerchrysler.com) "LISP is worth learning for the profound enlightenment experience you will have when you finally get it; that experience will make you a better programmer for the rest of your days." -- Eric S. Raymond
- Next message: Jignesh: "Re: Developing Proxy Server - Don't have enough speed"
- Previous message: nitin_panj: "Makefile utility"
- Maybe in reply to: Default User: "Re: char ** realloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] [ attachment ]
Relevant Pages
|
|