函数返回值

本文通过一系列测试函数,展示了C语言中指针使用及内存管理的常见问题,包括返回局部变量地址导致的警告和内存泄漏风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <malloc.h>

#define OVERFLOW -1
int main(void)
{
 int *x = NULL;
 int *y = NULL;

 int* test1();
 int* test2();
 int* test3();
 int* test4();
 int* test5();
 int* test6();
 int* test7();
 int* test8();

 printf("test1: %d/n",*test1());
 printf("test2: %d/n",*test2());
 x = test3();
 printf("test3: %d/n",*x);
 if(NULL != x)
   free(x);

 printf("test4: %d/n",*test4());
 printf("test5: %d/n",*test5());
 printf("test6: %d/n",*test6());
 printf("test7: %d/n",*test7());

 y = test8();
 printf("test8: %d/n",*y);
 if(NULL != y)
   free(y);

 return 0;
}

/*有一个警告,说warning : returning address of local variable or temporary*/
int* test1(void)
{
 int a = 1;
 return &a; 
}

int* test2(void)
{
 int a = 2;
 int *p = &a;
 return p;
}

int *test3(void)
{
 int *a = (int *)malloc(sizeof(int));
 if(NULL == a)
 {
  return NULL;
 }
 *a = 3;
 return a;
}

/*也有一个警告,同test1()*/
int *test4(void)
{
 int a = *test1();  /*调用test1(),*/
 return &a;
}

/*由于test1()返回的是局部变量的地址,所以在test4()返回后,
test1()中的局部变量已经被释放,所以test4()返回的指针指向
的内容已经不再存在*/

int *test5(void)
{
 int a = *test2();  /*调用test2(),*/
 return &a;
}

int *test6(void)
{
 int *p = test2();  /*调用test2(),*/
 return p;
}

int *test7(void)
{
 int p = *test3();  /*调用test3(),返回的是局部变量p的地址,test3中申请有内存将出现泄露*/
 return &p;
}

int *test8(void)
{
 int *p = test3();  /*调用test3(),返回的是指针变量p的地址*/
 return p;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值