在成为自由函数时,内存使用?(C编程) [英] When will memory used in a function become free ??(C programming)

查看:88
本文介绍了在成为自由函数时,内存使用?(C编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是code

的code:

 的#include<&stdio.h中GT;为int * NUM(无效);INT主要(无效)
{
    INT * NUM2;
    NUM2 = NUM​​();
    的printf(%d个\\ N,* NUM2);    返回0;
}
为int * NUM(无效)
{
    INT NUM = 20;    返回试验#;
}

问题:


  1. 据我们所知,函数 NUM 是本地其功能 NUM(),所以在这code我尝试在函数返回变量 NUM 的地址,调用它的函数,这是的main()


  2. 在我刚才用的对其操作提取特定 NUM 变量的值,并打印出来在的main() 功能。


  3. 有一件事我很困惑。我记得我读了一本关于JavaScript的提及一个变量寿命的功能,这意味着该函数完成执行其指令,并通过控制返回到调用它的功能后,内,每个变量的函数中的值将是干净的出(垃圾收集器),但为什么在这个code我的的main()功能仍然可以指向特定的内存地址?值



解决方案

您可以看到变量的值是因为如何栈作品的原因。有效地输入函数 NUM ,指针(堆栈指针)移动到增加空间功能的本地存储。当您退出功能堆栈指针向后移动有效地意味着,在未来的函数调用将覆盖在previous函数调用使用的堆栈存储器。直到它被覆盖,但是,该值存在处于一个中间的。它仍然居然还有在内存中,但随时可能会被覆盖。的实际值的存在,可能会或可能不会是这种情况。这就是为什么做,你上面做称为的未定义行为

基本上...不这样做。

Below is the code

The Code:

#include <stdio.h>

int * num(void);

int main(void)
{
    int * num2;
    num2 =num();
    printf("%d\n" , *num2);

    return 0;
}


int * num(void)
{
    int num = 20;

    return &num;
}

The Question :

  1. As we know , the function num is local to its function num() , so in this code I try to return the address of the variable num in the function to the function that calls it , which is main().

  2. After that I just use the dereferencing operator to extract the value of the specific num variable and print it out in main() function.

  3. There's one thing i'm confused . I remember i read a book about javascript that mention a variable lifetime is within the function , which mean after the function finish performing its instructions and pass the control back to the function that calls it , the value of each variable in the function will be clean out(garbage collector).But why in this code my main() function still can point to the value of that specific memory address??

解决方案

The reason you can see the value of the variable is because of how the stack works. Effectively as you enter the function num, a pointer (the stack pointer) is moved to add space in for the local storage of the function. When you exit the function the stack pointer is moved back effectively meaning that the next function call will overwrite the stack storage used in the previous function call. Until it is overwritten, however, the value exists in a sort of limbo. It's still actually there in memory but may get overwritten at any moment. The existence of the actual value there may or may not be the case. That is why doing as you do above is known as undefined behaviour.

Basically ... don't do it.

这篇关于在成为自由函数时,内存使用?(C编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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