Stack Memory Basics

Consider this code:

 char* foo(int myNum) {
    char* StrArray[5] = {"TEST","ABC","XYZ","AA","BB"};

    return StrArray[4];
 }

When I return to the StrArray[4]caller, should this work? Since the array is defined on the stack when the caller receives the pointer, this part of the memory is out of scope. Or will this code work?

+3
source share
5 answers

This code will work. You return a pointer value in StrArray[4]that points to the string constant "BB". Constant lines have a life expectancy equal to the life of your entire program.

The lifetime of the pointer is important, not the location of the pointer. For example, the following similar code will not work:

char* foo(int myNum) {
   char bb[3] = "BB";
   char* StrArray[5] = {"TEST","ABC","XYZ","AA",bb};

   return StrArray[4];
}

, bb foo() , .

+8

: .

StrArray char *;
, char *.
, .

C - const.

:

const char* foo(int myNum) {
   const char* StrArray[5] = {"TEST","ABC","XYZ","AA","BB"};

   return StrArray[4];
}
+4

. , (StrArray[4]), "BB". C - , , , (.. ). , . , .

, , const char* .

+2

C , 0. , StrArray [0]

, StrArray [5] .

C will allow you to write code to return StrArray [5], but wht is undefined and will be different from the OS and the compiler, but will often cause the program to crash.

0
source

The stack contains only an array of pointers, not string constant literals.

0
source

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


All Articles