When you return stringg, which is a pointer to the local variable string in GetString, you are returning a reference to memory that is just about to be reclaimed. This is because string "lives" in the stack frame of GetString, and the stack frame ceases to exist when the function returns. You have three options:
- Move
string to main, and pass a pointer to it to GetString.
- Dynamically allocate
string using malloc inside of GetString. Memory allocated using malloc survives until manually released using free.
- Or, as Michael Petch pointed out below, declare
string as static, meaning memory will be set aside in the global data segment of the program. However, this means that subsequent calls to GetString will clobber its contents, so if you want to save the result of a previous call to
GetString you must manually copy it using strdup or similar.
Before GetString returns, the stack looks something like this:
(high address)
+---------------------+
| (main's frame) |
| ... |
+---------------------+
| (GetString's frame) |
| char string[100] |
+---------------------+ <- stack pointer
(low address)
As you can see, the stack pointer points to the end of GetString's frame, marking the top of the stack (notice that on most modern platforms, the stack actually grows downwards). But when GetString returns, the stack pointer moves up to the end of main's frame:
(high address)
+---------------------+
| (main's frame) |
| ... |
+---------------------+ <- stack pointer
| Formerly the frame |
| of GetString, now |
| (probably) garbage. |
+---------------------+
(low address)
And accessing something that is not part of the stack (i.e., in this case below the stack pointer) results in undefined behavior. (Well, not quite - see Barak Manos' comment below) In your case, you get garbage.
stringgis a local variable and you can return a pointer to it. It's undefined behaviour.counterso that it doesn't exceed the size of your array.stringg. When an array appears in an expression in C, it is (roughly speaking) transformed into a pointer to its first element, so you could simplyreturn string.maindoesn't know what yourGetStringfunction is. If you are using a 64 bit system, your compiler most likely will be things wrong. You should compile your code with all warnings enabled.