[clug-progsig] realloc()

Cade Cairns cairnsc at gmail.com
Sun Feb 20 08:43:39 PST 2005


You are missing a closing ')' character in the second argument of the
first realloc() call. This affects the code for the rest of the file
(or until a matching ')' is found), which would have caused the second
error. You should hvae:

    ptr = realloc(NULL, ((strlen(array) + 1) * sizeof(char)));

Alternatively you could remove the first '(' in the second argument
since it is not needed:

    ptr = realloc(NULL, (strlen(array) + 1) * sizeof(char));

On Sat, 19 Feb 2005 20:03:28 -0700, Rob S <rob.s at telus.net> wrote:
> I've been learning C and I'm having a bit of trouble allocating memory
> with realloc() in two instances.
> 
> gcc is rejecting each instance.
> 
> I'd like to find out the correct useage of realloc() when allocating
> memory from a null pointer, and to free said memory with realloc() when
> its not needed anymore.
> 
> Here's the code i've typed up. I was wondering if the members of the
> list could look at it and provide some advice?
> 
> ---
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> 
> main()
> {
>     char *ptr, array[] = "This is a string.";
>     int termination;
> 
>      /* this is where the first problem is. The code is used as its used
> in the book, but gcc isnt accepting it, and i dont know why. When i try
> to compile it, gcc spits out: parse error before ';' token. */
>     ptr = realloc(NULL, ((strlen(array) + 1) * sizeof(char));
>     if (ptr != NULL)
>     {
>         termination = 0;
>         strcpy(ptr, array);
>         printf("%s\n", ptr);
>     /* I think this is where the problem is, but gcc says there's a
> parse error before "else", two lines ahead. I'm not sure whats going on
> here either. In the manual i'm following, the code should compile as
> written. I really dont know whats going on */
>         ptr = realloc(ptr, 0);
>     }
>     else
>     {
>        printf("realloc() failed, exiting.\n");
>        termination = 1;
>     }
> 
>     return termination;
> }
> 
> -----
> 
> I havent had any problems with malloc(), calloc() or free(). I'll see if
> i can find some errata on the text, if there is any still on the net for
> this book.



More information about the clug-progsig mailing list