Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static data memory limit in C++ application

Tags:

c++

c

Someone has written function in our C++ application and is already in the production and I don't know why it's not crashing the application yet. Below is the code.

char *str_Modify()
{
    char buffer[70000] = { 0 };
    char targetString[70000] = { 0 };

    memset(targetString, '\0', sizeof(targetString));

    ...
    ...
    ...
    return targetString;
}

As you can see, the function is returning the address of a local variable and the allocated memory will be released once the function returns. My question

  • Wanted to know what is the static data memory limit?
  • What can be the quick fix for this code? Is it a good practice to make the variable targetString static?
like image 352
NJMR Avatar asked Jan 04 '23 04:01

NJMR


2 Answers

(Note that your call to memset has no effect, all the elements are zero-initialised prior to the call.)

It's not crashing the application since one manifestation of the undefined behaviour of your code (returning back a pointer to a now out-of-scope variable with automatic storage duration) is not crashing the application.

Yes, making it static does validate the pointer, but can create other issues centred around concurrent access.

And pick your language: In C++ there are other techniques.

like image 148
Bathsheba Avatar answered Jan 05 '23 19:01

Bathsheba


Returning targetString is indeed UB as other answers have said. But there's another supplemental reason why it might crash on some platforms (especially embedded ones): Stack size. The stack segment, where auto variables usually live, is often limited to a few kilobytes; 64K may be common. Two 70K arrays might not be safe to use.

Making targetString static fixes both problems and is an unalloyed improvement IMO; but might still be problematic if the code is used re-entrantly from multiple threads. In some circumstances it could also be considered an inefficent use of memory.

An alternative approach might be to allocate the return buffer dynamically, return the pointer, and have the calling code free it when no longer required.

As for why might it not crash: if the stack segment is large enough and no other function uses enough of it to overwrite buffer[] and that gets pushed first; then targetString[] might survive unscathed, hanging just below the used stack, effectively in a world of its own. Very unsafe though!

like image 34
NickJH Avatar answered Jan 05 '23 19:01

NickJH