Re: char ** realloc
From: Al Bowers (abowers_at_combase.com)
Date: 04/30/03
- Next message: Valentin Nechayev: "Re: timer implementation"
- Previous message: David W Noon: "Re: char ** realloc"
- In reply to: Joshua Jones: "char ** realloc"
- Next in thread: Neil Cerutti: "Re: char ** realloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] [ attachment ]
Date: Wed, 30 Apr 2003 06:47:47 -0400
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;
> ...
It appears that you have failed to initialize result.
The argument to function realloc must either be NULL or
a value that has been previously returned by function
realloc, malloc, or calloc. Since it is uninitialized,
you have no idea on what value it represents. So do,
char ** result = NULL; /* initializes */
>
> result = realloc (result, (((*count)+1) *
> sizeof (char *)));
Here, the 1st argument to realloc, result, may representing
a pointer to previously allocated memory. Using that same
variable to store the return of realloc is dangerous. Should
realloc fail you have lost the access to the previously
allocations, and result in a memory leak since you are unable
to free it.
> if (result == NULL)
> fprintf(stderr, "Realloc failed\n");
>
If the return value is NULL, then the allocation failed.
You need to do more than just print the warning. You cannot
continue as if nothing happened.
> result[*count] = malloc (strlen(inet_ntoa(
> recv_iphdr->ip_src))+1);
> if (result[*count] == NULL)
> fprintf(stderr, "malloc failed\n");
>
I suggest changes like this:
char **result = NULL, **temp;
...
temp = realloc (result, (*count+1)*sizeof(*result));
if (temp == NULL)
{
fprintf(stderr, "Realloc failed\n");
free(result);
exit(EXIT_FAILURE); /* or whatever */
}
result = temp;
/* continue with with malloc */
---------
Al Bowers
Tampa, FL. USA
abowers@combase.com
http://www.geocities.com/abowers822
comp.lang.c
- Next message: Valentin Nechayev: "Re: timer implementation"
- Previous message: David W Noon: "Re: char ** realloc"
- In reply to: Joshua Jones: "char ** realloc"
- Next in thread: Neil Cerutti: "Re: char ** realloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] [ attachment ]
Relevant Pages
|