Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack memory fundamentals

Tags:

c

stack

Consider this code:

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

    return StrArray[4];
 }

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

like image 501
Jitesh Avatar asked Feb 11 '26 18:02

Jitesh


2 Answers

This code will work. You are returning the value of the pointer in StrArray[4], which points to a constant string "BB". Constant strings have a lifetime equal to that of your entire program.

The important thing is the lifetime of what the pointer points to, not where the pointer is stored. For example, the following similar code would not work:

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

   return StrArray[4];
}

This is because the bb array is a temporary value on the stack of the foo() function, and disappears when you return.

like image 138
Greg Hewgill Avatar answered Feb 14 '26 18:02

Greg Hewgill


Beware: you're lying to the compiler.

Each element of StrArray points to a read-only char *;
You're telling the compiler the return value of your function is a modifiable char *.
Lie to the compiler and it will get its revenge sooner or later.

In C, the way to declare a pointer to read-only data is to qualify it with const.

I'd write your code as:

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

   return StrArray[4];
}
like image 42
pmg Avatar answered Feb 14 '26 18:02

pmg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!