Sign in to follow this  
asdqwe

stack problem

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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'...

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this