-5

What are the possible behaviors of the program below?

I have tried to allocate and use memory on stack, and print the memory block pointed by p, output are characters of '\0'.

I known technically it is not available when the function returns.

However, why not the program crash, or print some random garbage?

#include <cstring>
#include <cstdio> 
#include <cstdlib> //malloc
char* getStackMemory(){
    char mem[10];
    char* p = mem;
    return p;
}


int main(){
    char* p  = getStackMemory();
    strcpy(p, "Hello!");
    printf("%s\n", p);
    for(int i = 0; i<10; i++){
         printf("%c\n", p[i]);
    }

    return 0;
}
  • 4
    These are very basic concepts covered in the first chapters of any of the zillion of tutorials that a 2-minute search will dig up. – dandan78 Aug 20 '14 at 08:10

4 Answers4

2

As per you already know that memory of char mem[10]; on stack and it is not available when the function returns. So i only says that it will cause you Undefined Behavior.

Community
  • 1
  • 1
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
0

It is because after the function returns, the stack is unavailable however u r returning the address of that location from that function which is getting stored in pointer p, so the program does not crash but gives garbage value.

0

why not the program crash, or print some random garbage?

The program will not crash as you are not accessing any illegal memory. The stack memory is a part of your program and as long as you are accessing the memory in a valid range the program will not crash. Yes, you can modify the stack memory whether the function is in that stack frame or not.

Now accessing the memory which is not in the current stack frame will lead to an Undefined Behavior. This is compiler dependent. Most of the compiler will print the garbage value. I don't know which compiler you are using!!

I would say try to understand the basic concept of stack memory in C/C++ programs. An I would suggest also look into heap memory.

Arpit
  • 767
  • 7
  • 20
0

Here, the program will not crash rather it will print some garbage value. When it will return stack will not be available and hence will give garbage value.

Ravi
  • 59
  • 3