C - 函数返回指向局部变量的指针 [英] C - function returning a pointer to a local variable

查看:32
本文介绍了C - 函数返回指向局部变量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码.

#include<stdio.h>
int *abc(); // this function returns a pointer of type int

int main()
{
    int *ptr;
    ptr = abc();
    printf("%d", *ptr);
    return 0;
}

int *abc()
{
    int i = 45500, *p;
    p = &i;
    return p;
}

输出:

45500

我知道根据 link 这种类型的行为是未定义的.但是为什么我每次运行程序时都会得到正确的值.

I know according to link this type of behavior is undefined. But why i am getting correct value everytime i run the program.

推荐答案

每次调用 abc 时,它都会标记"堆栈顶部的一个区域作为它将写入所有它的局部变量.它通过移动指示栈顶位置的指针来实现.该区域称为堆栈帧.当函数返回时,它通过将堆栈指针移到原来的位置来表明它不想再使用该区域.因此,如果您之后调用其他函数,它们将出于自己的目的重用堆栈的该区域.但是就您而言,您还没有调用任何其他函数.所以堆栈的那个区域保持相同的状态.

Every time you call abc it "marks" a region at the top of the stack as the place where it will write all of its local variables. It does that by moving the pointer that indicates where the top of stack is. That region is called the stack frame. When the function returns, it indicates that it does not want to use that region anymore by moving the stack pointer to where it was originally. As a result, if you call other functions afterwards, they will reuse that region of the stack for their own purposes. But in your case, you haven't called any other functions yet. So that region of the stack is left in the same state.

以上所有内容都解释了您的代码的行为.没有必要所有 C 编译器都以这种方式实现函数,因此您不应该依赖这种行为.

All the above explain the behavior of your code. It is not necessary that all C compilers implement functions that way and therefore you should not rely on that behavior.

这篇关于C - 函数返回指向局部变量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆