Question

I'm trying to learn and understand dynamic memory in c++, I'm not on my home computer so I'm using an online compiler (gcc 4.1.8) and I'm seeing an interesting thing occur:

The first program prints 1 and throws an error:

#include <iostream>
int main() {
    int i[1];
    i[0] = 1;
    i[1] = 2;
    std::cout<<i[0]<<endl;
    std::cout<<i[1]<<endl;
    return 0;
}

The second program prints 1 and 2 and then keeps prints a 0:

#include <iostream>
int main() {
    int* i = new int[1];
    i[0] = 1;
    i[1] = 2;
    std::cout<<i[0]<<endl;
    std::cout<<i[1]<<endl;
    std::cout<<i[2]<<endl;
    return 0;
}

My guess as to why this happens is that dynamic memory is a predefined space in the stack(or wherever its kept) that has already been cleared to zero at the beginning of a program so that when you use the operator new the program goes to this place and finds a length of unused bytes long enough for your request and returns the first memory value of that to your pointer and because its all been defined already its possible for me to go to the next value and read it.

Was it helpful?

Solution

Typically, memory allocators pull from a single pool that is used to allocate objects of various types. Often, they use the block of memory to keep track of its own accounting information while it's free. Each of these things imposes a certain minimum size on each block. The former because each block must meet the implementation's most severe alignment requirement. The latter because each block typically must be at least big enough to hold two pointers and an integer (pointer to previous free block, pointer to next free block, and size of block).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top