stack problem

Started by
5 comments, last by asdqwe 16 years, 2 months ago
I have in my (C++ Console App)prog a line: char chr[100000000]; When I run it it gives a runtime error; if I debug it, it says "stack overflow". How can I solve this type of problems? And why doesn't this error show at compile-time?
Advertisement
It doesn't give an error at compile-time because the linker sets the stack size so the compiler doesn't know it.

You can do either:

1. char * chr;
... some time later ...
chr = malloc(what_size_you_need);

2. use a std:string.

if you're storing a string in there, no need to allocate that huge ammount of stack 'just to make sure it covers all cases'...
Q: How many programmers does it take to write a nice piece of software?A: MORE.
What could you possibly need a hundred million character buffer for?

As cobru mentioned, large allocations should go on the heap (i.e., be allocated with new or, in C, malloc), stack space is very limited, and is certainly less than 100000000 bytes.
Quote:Original post by cobru
1. char * chr;
... some time later ...
chr = malloc(what_size_you_need);

In this case don't forget, as soon as you no longer need chr, to call free(chr)!
Quote:Original post by Nyarlath
In this case don't forget, as soon as you no longer need chr, to call free(chr)!


Also, make sure to free(chr) if you would lose all references to it. For instance, the following piece of code contains a memory leak:
char *txt = malloc(42);frobnicate(txt);free(txt);


This is because frobnicate can throw an exception and thus skip the release of the text (which would lead to leaking the corresponding memory). Thus, in C++, using dynamic memory directly should always involve try-catch(...)-throw blocks:
char *txt = malloc(42);try {  frobnicate(txt);}catch(...) {  free(txt);  throw;}free(txt);


Which is why most C++ programmers either write leaky programs or use std::string.
Don't use malloc/free. Use new/delete.
Thanks everybody.

This topic is closed to new replies.

Advertisement