C语言正确返回指针函数返回的有用内容

C语言学习时遇到的基本的问题:

1.在某一指针函数内声明的局部变量,在返回(return)时该返回指针对应内存地址的值会变化。

 在函数中开辟的栈会因为函数的结束被系统回收,栈中存放的数据不再可靠,返回在函数内赋值的指针,其地址指向的内容在别的函数中无法使用。

比如在这段函数中返回指针b,结果并不是sum的值。

#include <stdio.h>
#include<stdlib.h>
int *test();
int main() {
    int *a=NULL;
    a = test( );
    printf("");
    printf("%d\n", *a);
    return 0;
}

    int *test() {
        int *b;
        int sum = 123;
        b = &sum;
        printf("%d\t%d\n",sum,*b);
        printf("%p\n",b);
        return b;
    }

运行结果:

 但是!如果去除 printf("");这段代码,即:

#include <stdio.h>
#include<stdlib.h>
int *test();
int main() {
    int *a=NULL;
    a = test( );
    printf("%d\n", *a);
    return 0;
}

    int *test() {
        int *b;
        int sum = 123;
        b = &sum;
        printf("%d\t%d\n",sum,*b);
        printf("%p\n",b);
        return b;
    }

运行结果:

得到的结果仍然为sum的值。这是因为在返回该内存时编译器还没有改动该段内存,在进行一个语句的运行后该段内存就会被VS编译器初始化为可用内存(0xcccccccc)。所以一个printf("");的区别才会导致这样的不同。

2.VS中对于未初始化的内存地址都赋值为cc(0xcccccccc)。

VS编译器的特点。 (linux终端会初始化为0x7ff)

3.某一函数内动态分配(malloc)的变量在函数结束后是否需要free。 

要解决内存在A函数结束就被刷新的问题,只有在A函数中开辟动态内存,将所需数据存入,并返回(return)该变量,在调用A函数的B函数中使用新的变量继续使用和释放该内存地址。

#include <stdio.h>
#include<stdlib.h>
int *test();
int main() {
    int *a=NULL;
    a = test( );
    printf(" ");
    printf("%d\n", *a);
    free(a);
    return 0;
}

    int *test() {
        int *b = (int*)malloc(sizeof(int));
        int sum = 123;
        *b = sum;
        printf("%d\t%d\n",sum,*b);
        printf("%p\n",b);
        return b;
    }

运行结果:

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值