[Sussex] More C programming help

Rupert Swarbrick rupert.swarbrick at lineone.net
Thu May 12 22:36:00 UTC 2005


Captain Redbeard wrote:
> Alright guys, explain this one!
>
> Here's the original program:
>
> #include <stdio.h>
> #include <stdlib.h>
>
> int main()
> {
>   int i = 0;
>   int ArraySize = 100;
>   char **CharArray;
>
>   CharArray = (char **) malloc (ArraySize);
>
>   int X = 100;
>
>   for (i=0; i<X; i++)
>   {
>     CharArray[i] = NULL;
>   }
>
>   printf ("free()ing CharArray.\n");
>   free (CharArray);
>   return 0;
> }
>
>
> This simply creates an array of strings, allocates memory to  the array,
> NULLs every element of the array and then frees the memory.  However
> when I run this I get the following:
>
> free()ing CharArray.
> *** glibc detected *** double free or corruption (out): \ 0x08049710 ***
> Aborted
>
> i.e. it got as far as the free() command and then crashed. Exploring
> this a bit I discovered that if I put the value of X at 25, that is NULL
> just the first 25 elements, the program compiles and runs fine and
> Valgrind is also happy with it but if I put X=26 then it crashes again.
> Further exploration revealed that whatever value I put ArraySize at the
> program will ALWAYS crash if X is more than ArraySize/4 but if X is only
> ArraySize/4 or less then no crash and no errors reported by Valgrind.
> This was the case even when I put ArraySize = 100,000,000.  If X was
> 25,000,000 then all is OK but if X = 25,000,001 then it crashes.
> Looking into this further I re-wrote the program as follows:
>
> #include <stdio.h>
> #include <stdlib.h>
>
> int main()
> {
>   int ArraySize = 100;
>   char **CharArray;
>
>   CharArray = (char **) malloc (ArraySize);
>
>   int X = 50;
>
>   CharArray[X] = NULL;
>
>   printf ("free()ing CharArray.\n");
>   free (CharArray);
>   return 0;
> }
>
> Now the program runs fine and doesn't crash but Valgrind reports a
> "Invalid write of size 4" in line 13 (CharArray[X] = NULL;).  It will do
> this for ANY value of X that is greater then ArraySize/4.  From this it
> seems that the command "(char **) malloc (ArraySize)" only allocates
> ArraySize/4 elements so that if I want to have ArraySize elements I
> should make the line "(char **) malloc (ArraySize*4)" which **seems** to
> work fine but why the hell would I need to do that?  What the hell am I
> missing?
>
Aah. And I see someone else beat me to it!

Rupert
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 374 bytes
Desc: OpenPGP digital signature
Url : http://mailman.lug.org.uk/pipermail/sussex/attachments/20050512/19bebe28/attachment.pgp 


More information about the Sussex mailing list