1

Probably I just lack understanding of how malloc works, but I don't see an error with my code:

int amount_integers = 2;
int *pointer_to_allocated_memory = (int*)malloc(amount_integers * sizeof(int));
for (int i = 0; i < amount_integers; i++)
{
    int *address = &(pointer_to_allocated_memory)[i * sizeof(int)];
    *(address) = 0;
}

I'd like to initialize memory for an arbitrary amount of integers (amount_integers could be something else than 2). However, the malloc in line 2 seems to misfunction. MSVC's debugger will break at this point (without having defined a breakpoint). When continuing, it will encounter an access writing violation at line 6 (*(address) = 0;) when i is 1.

What I think I'm accessing:

    v pointer_to_allocated_memory[0 * sizeof(int)]
... | sizeof(int) | sizeof(int) | 
                  ^ pointer_to_allocated_memory[1 * sizeof(int)]

These should be allocated. Why does the application crash?

Julian B
  • 402
  • 1
  • 7
  • 15
  • 2
    The [] operator already multiplies by `sizeof(int)`. You are indexing beyond the end of the memory and corrupting the heap. – Raymond Chen Apr 12 '14 at 12:45

2 Answers2

3

The array index is not indexing bytes but array elements, in your case ints:

       int *address = &(pointer_to_allocated_memory)[i];

valid values for i are 0 and 1

thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
1

Because you misunderstand how pointer arithmetic works. It doesn't work with bytes, it works with chunks of memory of sizeof(T) bytes, T being the pointer's pointed type. So

int *address = &(pointer_to_allocated_memory)[i * sizeof(int)];

should be

int *address = &ptr[i];

instead. (Also note the lack of superfluous parenthesizing and simpler name...)

By the way, casting malloc is harmful.

Community
  • 1
  • 1