[clug-progsig] realloc()
Rob S
rob.s at telus.net
Sat Feb 19 19:03:28 PST 2005
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.
-Rob.
More information about the clug-progsig
mailing list