Search code examples
cpointersmallocdynamic-memory-allocation

Another dynamic memory allocation bug


I'm trying to allocate memory for a multidimensional array (8 rows, 3 columns).

Here's the code for the allocation (I'm sure the error is clear for you)

char **ptr = (char **) malloc( sizeof(char) * 8);

for (i = 0; i < 3; i++)
    ptr[i] = (char *) malloc( sizeof(char) * 3);

The crash happens when I reference this:

ptr[3][0];

Unhandled exception at 0x0135144d in xxxx.exe: 0xC0000005: Access violation writing location 0xabababab.

Are there any recommended references/readings for this kind of subject?

Thanks.


Solution

  • The first malloc() is wrong. It should be:

    malloc(sizeof(char*) * 8)
    

    A char* is 4 byte (or 8 byte... see P.S) whereas char is 1 byte. When you write ptr[3] the compiler will assume that you want to access to the base address of ptr + 3*sizeof(char*). So you will access to memory that you didn't allocate.

    P.S:

    To be more precise, char* is 4 byte on 32 bit systems and 8 byte on 64 bit systems.