简体   繁体   English

C 指针问题 - 局部变量的地址可能会转义函数

[英]C pointer problem - Address of local variable may escape the function

Here is my code:这是我的代码:

int* return_to_main()
{
    int george = 32;
    int* pointer;
    pointer = &george;
    printf("george address: %p\n", (void *)&george);
    printf("george content: %d\n", *pointer);
    return pointer;
}

int main()
{
    int* test = return_to_main();
    printf("test address: %p\n", (void *)&test);
    printf("test content: %d\n", *test);
}

and it returns:它返回:

george address: 0061FEE8
george content: 32
test address: 0061FF1C
test content: 6422476

CLion says that "Address of local variable may escape the function". CLion 说“局部变量的地址可能会转义函数”。 How do I fix this?我该如何解决? And why is variable george and test's address and contents different?为什么变量乔治和测试的地址和内容不同? Is it normal that variable george and variable test's address are different???变量george和变量test的地址不一样正常吗???

"Address of local variable may escape the function". “局部变量的地址可能会转义函数”。

The reason for that is you are returning the address of local variable, you should not do that instead return by value or use dynamic memory allocation/ global variable etc.原因是您正在返回局部变量的地址,您不应该这样做,而是按值返回或使用动态内存分配/全局变量等。

one way to resolve your warning is below解决警告的一种方法如下

#include <stdio.h>
#include <stdlib.h>

int* return_to_main()
{
    int george = 32;
    int* pointer;
    pointer = malloc(sizeof(int));
    if ( !pointer ) {
        printf("malloc failed\n");
        return NULL;
     }
    *pointer = george;
    printf("george address: %p\n", (void *)&george);
    printf("pointer : %p\n", pointer);
    printf("george/pointer content: %d\n", *pointer);
    return pointer;
}

int main()
{
    int* test = return_to_main();

    if(test)
    {
        printf("test address: %p\n", (void *)test);
        printf("test content: %d\n", *test);
        free(test);
        test = NULL;
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM