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?