Jitesh
Jitesh

Reputation: 31

Stack memory fundamentals

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?

Upvotes: 3

Views: 499

Answers (5)

Clifford
Clifford

Reputation: 93566

Only the array of pointers is on the stack, not the string-literal-constants.

Upvotes: 0

pmg
pmg

Reputation: 108986

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];
}

Upvotes: 4

AnT stands with Russia
AnT stands with Russia

Reputation: 320787

The code will work. The point you are returning (StrArray[4]) points to a string literal "BB". String literals in C are anonymous array objects with static storage duration, which means that they live as long as your program lives (i.e forever). It doesn't matter where you create that sting literal. Even if it is introduced inside a function, it still has static storage duration.

Just remember, that string literals are not modifiable, so it is better to use const char* pointers with string literals.

Upvotes: 2

mmmmmm
mmmmmm

Reputation: 32720

C uses arrays with indicies beginning at 0. So the first element is StrArray[0]

Thus StrArray[5] was not declared in your code.

C will allow you to write code to return StrArray[5] but wht happens is undefined and will differ on OS and compiler but often will crash the program.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994897

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.

Upvotes: 8

Related Questions