Interesting replies, thanks for the insights. Now I get what's going on with memory in C.
Thanks again all
Printable View
Interesting replies, thanks for the insights. Now I get what's going on with memory in C.
Thanks again all
Actually, the above code requires 20 * sizeof(int), which is commonly 80 bytes [40 bytes on a 16-bit (DOS) compiler] - but yes, it would crash with immediate effect if you don't have sufficient space on the stack - depending on the implementation of the OS you either get a specific "Stack overflow" or a generic "Invalid memory access" type error [or in the case of a DOS application, possibly some plain strange behaviour].
There is no standard way of knowing how much stack-space is "available", and this is one very good reason for NOT using large variables in stack-space. In a Windows or Linux application, the stack may be about 1MB. In most cases, you can tell the compiler (or more concretely the linker) the size of stack you want, so if you have some application that really needs huge amounts of stack-space, then you can "fix it". In embedded systems, the stack may be anything from a few hundred bytes and up.
Using the heap is safer, because there is the possibility of checking if the allocation worked, and if not, do something "useful" [like telling the user that you ran out of memory].
Also to clarify, both the stack and the heap are "RAM" resources. The difference is that the stack has to be ONE LINEAR space (aka contiguous), so it has to be pre-determined where it is in the system. The heap only needs to be linear in each individual allocation, each call to malloc or new can quite happily get a different chunk of memory that is completely separate from any other allocation, so we don't need to "decide early on" how large the heap is, or where it is located.
If you want to try to see how much stack space you are using, you could try something like this:
Code:#include <stdio.h>
char *stackBase;
void printStackUsage(int x)
{
char here;
char *p = &here;
unsigned long usage = stackBase - p;
printf("x = %d, %lu bytes used\n", x, usage);
}
void recurse(int x)
{
if (x < 50000) {
if (!(x % 500))
printStackUsage(x);
recurse(x+1);
if (!(x % 500))
printStackUsage(x);
}
}
int main(int argc, char **argv)
{
stackBase = (char *)&argv;
recurse(0);
return 0;
}
--
Mats
Of course, you could, but still practice is incredibly discouraged, not to mention you'll need assembly to do it since C/C++ can't do that. And as mentioned, desutrctors are called on objects, so their state is not valid anymore and its contents lost.