Use memory on stack

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 ''.

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("%sn", p);
    for(int i = 0; i<10; i++){
         printf("%cn", p[i]);
    }

    return 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.


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.


这是因为在函数返回之后,堆栈不可用,但是从返回存储在指针p中的那个函数返回该位置的地址,所以程序不会崩溃,而是给出垃圾值。

链接地址: http://www.djcxy.com/p/79904.html

上一篇: 内存分配堆栈

下一篇: 在堆栈上使用内存