[Sussex] C programming help - again!
Jim Nicholson
jim.nicholson at newlinesystems.co.uk
Tue May 10 05:45:30 UTC 2005
Captain Redbeard wrote:
> Hi everybody!
>
> Consider the following program:
>
>
>
> #include <stdlib.h>
> #include <stdio.h>
>
> int main()
> {
> struct TestStruct
> {
> int X;
> int Y;
>
> char *CharString;
> } *TestStructPtr;
>
> TestStructPtr = malloc (sizeof (struct TestStruct));
> TestStructPtr->CharStr = malloc ((sizeof (char)) * 16);
This allocates 16 bytes (the sizeof(char) is superfluous as the C
standard guarantees it will always be 1) and sets
TestStructPtr->CharString to point to it
>
> TestStruct->X = 3;
> TestStruct->Y = 4;
> TestStruct->CharString = "Hello World!\n\n\n");
This sets TestStructPtr->CharString to point to the string literal
"Hello World!\n\n\n". The block of memory malloced above is no longer
pointed to, this is you memory leak.
>
> printf ("TestStructPtr = (%i, %i).\n\n", TestStructPtr->X,
> TestStructPtr->Y);
> printf ("CharString = %s.", TestStructPtr->CharString);
>
> free (TestStructPtr);
This frees the memory allocated to the structure.
>
> return 0;
> }
[snip]
> .
> .
> .
> printf ("TestStructPtr = (%i, %i).\n\n", TestStructPtr->X,
> TestStructPtr->Y);
> printf ("CharString = %s.", TestStructPtr->CharString);
>
> free (TestStruct->CharString);
> free (TestStructPtr);
>
> *** glibc detected *** free(): invalid pointer: 0x080485b4 ***
Here you are trying to free the memory used by the string literal "Hello
World!\n\n\n" which was not allocated by malloc, hence the invalid
pointer error.
To fix this problem, use:
...
TestStructPtr = malloc (sizeof (struct TestStruct));
TestStructPtr->CharString = malloc (16);
TestStructPtr->X = 3;
TestStructPtr->Y = 4;
strcpy(TestStructPtr->CharString, "Hello World!\n\n\n");
printf ("TestStructPtr = (%i, %i).\n\n", TestStructPtr->X,
TestStructPtr->Y);
printf ("CharString = %s.", TestStructPtr->CharString);
free (TestStructPtr->CharString);
free (TestStructPtr);
...
This copies the "Hello World!\n\n\" string literal into the malloced
memory pointed to by TestStructPtr->CharString rather than making
TestStructPtr point to the string literal, so you are freeing up the
malloced memory.
Jim
More information about the Sussex
mailing list