Jump to content
  • Advertisement
Sign in to follow this  
asdqwe

stack problem

This topic is 3795 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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'...

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 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)!

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!