Reputation: 7804
As I understood that the following code generate variable length arrays (via a non standard extension of C++).
int main()
{
int valone = rand();
int valtwo = rand();
int array[valone][valtwo];
// Printing size
cout << sizeof(array) << endl;
}
Is there any way to check whether its generated on stack or heap? The wikipedia description here says that gcc
generates the same in stack, but when I tried above code, most of the times, the array size seems too big to fit into stack, but it never complains.
Note: This code works only with gcc & clang and not with visual studio
Upvotes: 3
Views: 493
Reputation: 238311
the array size seems too big to fit into stack, but it never complains.
By "never complains", I presume you mean that the program doesn't crash.
You never touch the memory that you allocate and the compiler was smart enough to prove it and didn't allocate anything.
Let us take the address of the variable, and send it to a function that is defined elsewhere:
int array[valone][valtwo] = {};
cout << &array << endl;
Now, the compiler wasn't quite so sure that the array is never accessed. That's because it can't go into the streaming operator which implemented in another translation unit. Perhaps the operator will dereference the pointer; we must make sure that the array exists.
Segfault crashed this program on my first attempt. The stack was overflown.
I suppose this kind of crash test is a way to test if VLA is on the stack.
Mikhail's suggestion in comments to compare adjacency of automatic variables to the VLA is a decent platform dependant idea, but it can only work if you allocate small enough VLA that it doesn't crash the program.
Upvotes: 1
Reputation: 1407
It might be a tricky question and I have tried some thing like
#include "iostream"
int Stack_or_heap(void* ptr)
{
int dummy;
return ptr > &dummy;
}
int main(int argc, char** argv)
{
int* i = new int();
int x, y, z;
std::cout << Stack_or_heap(&x) << Stack_or_heap(&y) << Stack_or_heap(&z) << Stack_or_heap(i);
}
Upvotes: 1
Reputation: 706
First I assume you know that any memory chunk allocated in the heap using either malloc or new continues its lifespan throughout the program unless explicitly deallocated. Thus we can conclude, if a variable length array only exists within its scope but not in the lifespan of the program, it is most probably allocated in the stack.
I don't know if there are cases where a chuck of memory is allocated in the heap but behaves as if it is a member of the stack. It is best the see the assembly code for that. Such implementation would probably use dynamic allocation functions/syscalls under the hood.
If it looks like a duck, walks like duck and talks like duck, then it should be safe to assume it is a duck(for the most of the time).
Upvotes: 0