Static data memory limit in C ++ application

Someone wrote a function in our C ++ application and is already in production, and I do not know why this is not an application failure. 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 returns the address of the local variable, and the allocated memory will be freed after the function returns. My question

  • I wanted to know what is the limit of static data memory?
  • What could be a quick fix for this code? Is it good practice to make a targetStringstatic variable ?
+4
source share
4 answers

(Note that your call is memsetnot valid, all elements are initialized to zero before the call.)

, undefined ( ) .

, static , , .

: ++ .

+6

C ++, .

:

#include <stdio.h>

int *f()
{
    static int a[10]={0};
    return a;
}
int main() 
{
    f();
    return 0;
}

GCC. [Live Demo]

, :

prog.c: In function 'f':
prog.c:6:12: warning: function returns address of local variable [-Wreturn-local-addr]
     return a;
            ^

. question, .

, int* fun (void) { static int i = 10; return &i; } versus int* fun (void) { int i = 10; return &i; },, . , undefined.

, tutorialspoint :

, , , C , .

+1

targetString - UB, . , ( ): . , , ; 64K . 70K .

targetString IMO; , . .

, , , .

, : , buffer[], ; targetString[] , , . , !

+1

, ?

. (, , ), . , , , .

?

.

char *modify(char *out, size_t outsz) {
    // ...
    return out;
}

( ).

targetString static?

. , , :

  • ~ 68 / . , - . memset , , .
  • static ( ) . :

    printf("%s,%s\n", str_Modify(1), str_Modify(2));
    

    , ( strtok, , ).

  • Since it is not repetitive, it is also not thread safe if you use multiple threads. This is a mess.
+1
source

Source: https://habr.com/ru/post/1689242/


All Articles