Gonzalo Solera
Gonzalo Solera

Reputation: 1192

A vector in the heap vs in the stack

Is the following correct?

"A vector in the heap (with sbrk or malloc) starts in the low address and goes to the high ones".

For example:

int *vec = sbrk(5*sizeof(int)):

vec[0] is in the address 0x500 and vec[1] is in 0x504.

But in the stack, int vec[5] goes from the high address to the low ones.

For example:

Is it right?

Upvotes: 2

Views: 130

Answers (4)

rcgldr
rcgldr

Reputation: 28808

I'm not aware of any PC based languages that use a stack like array (std::stack is last in first out, but I don't think its addressed top down).

IBM mainframes, some ARM tool sets, and other platforms have a block ended by symbol (.bes) segment type, where the name of the array points to the end of the array (1 past the last element), so the array would be addressed similar to a stack (top down). I don't know what languages support this, other than assembly language.

Upvotes: 0

Agent_L
Agent_L

Reputation: 5411

No. "starts in the low address and goes to the high ones" refer to subsequent allocs. Within one block, it's always the same way.

Besides, you only malloc a block, the block doesn't know if it's a vector of two int32's or just one int64. It's only after you cast it into int* that you're applying "internal structure" to it. Or, to be more precise, the "structure" is used only when a pointer is dereferenced.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This is absolutely not right: offsets between consecutive addresses of logical elements of an array must always be the same in both their sign and magnitude. Otherwise, this simple code would not work:

void foo(int *a, size_t p, int k) {
    a[p] = k;
    printf("%d\n", a[p]);
}
...
int *x = malloc(5*sizeof(int));
int y[5];
foo(x, 2, 3);
foo(y, 2, 3);

What could go up and down is addresses of different arrays allocated in the dynamic and in automatic memory. For example, if you do this

int *x1 = malloc(5*sizeof(int));
int *y1 = malloc(5*sizeof(int));

vs. this

int x2[5];
int y2[5];

the relative addresses of &x1[0]/&y1[0] vs. &x2[0]/&y2[0] could be in opposite direction. However, even this is not guaranteed, because all of this is up to implementation.

Upvotes: 2

alain
alain

Reputation: 12037

No, this is not true.

While usually the stack "goes down", this is only valid for adding new objects to it. The content of the objects themselves is still in the same order as if allocated on the heap.

Else you could not do pointer arithmetics.

Upvotes: 6

Related Questions