Chinaunix首页 | 论坛 | 博客
  • 博客访问: 663367
  • 博文数量: 209
  • 博客积分: 26
  • 博客等级: 民兵
  • 技术积分: 326
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-21 09:29
文章分类

全部博文(209)

文章存档

2015年(6)

2014年(40)

2013年(154)

2012年(11)

我的朋友

分类: C/C++

2014-08-13 08:53:11

1:概述
      C语言中是不允许返回局部变量的,因为局部变量分配在栈上,函数返回后内容就会被销毁,所以你得到的
值将是乱码,但是C编译器也有可能会帮你优化,让返回正确的值,但我们永远不要依赖编译器。

2:例
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. char *
  5. tst_var_0(void)
  6. {
  7.     char s[128] = "hello";

  8.     return s;
  9. }

  10. char *
  11. tst_var_1(void)
  12. {
  13.     return "hello";
  14. }

  15. char global_array[128];

  16. char *
  17. tst_var_2(void)
  18. {
  19.     strcpy(global_array, "hello");
  20.     return global_array;
  21. }

  22. char *
  23. tst_var_3(void)
  24. {
  25.     static char buf[128];
  26.     strcpy(buf, "hello");

  27.     return buf;
  28. }

  29. char *
  30. tst_var_4(void)
  31. {
  32.     char *s = (char *)malloc(128);
  33.     strcpy(s, "hello");

  34.     return s;
  35. }

  36. void
  37. tst_var_5(char *res)
  38. {
  39.     strcpy(res, "hello");
  40. }

  41. int
  42. main(int argc, char **argv)
  43. {
  44.     printf("%s\n", tst_var_0());
  45.     printf("%s\n", tst_var_1());
  46.     printf("%s\n", tst_var_2());
  47.     printf("%s\n", tst_var_3());
  48.    
  49.     char *tmp = tst_var_4();
        printf("%s\n", tmp);
        free(tmp);
  50.     
  51.     char *res = (char *)malloc(128);
  52.     memset(res, 0, 128);
  53.     tst_var_5(res);
  54.     printf("%s\n",res);

  55.     free(res);
  56.     return 0;
  57. }

3:结果(你能想想到吗)
  1. xdzh@xdzh-laptop:/media/home/work/c$ gcc -Wall -O2 -o tst-auto tst-auto.c
  2. tst-auto.c: In function ‘tst_var_0’:
  3. tst-auto.c:10: warning: function returns address of local variable
  4. xdzh@xdzh-laptop:/media/home/work/c$ ./tst-auto
  5. hello
  6. hello
  7. hello
  8. hello
  9. hello
  10. hello
  11. xdzh@xdzh-laptop:/media/home/work/c$ gcc tst-auto.c
  12. tst-auto.c: In function ‘tst_var_0’:
  13. tst-auto.c:10: warning: function returns address of local variable
  14. xdzh@xdzh-laptop:/media/home/work/c$ ./a.out
  15. h@
  16. hello
  17. hello
  18. hello
  19. hello
  20. hello
第一编译我们采用了优化模式,虽然产生了警告,但是我们得到了正确的结果,第二次编译器不干了,很遗憾。

4:注
   我们看到有很多中方法避免返回乱码的局部变量。
  • 返回一个指向字符串常量的指针,(简单,局限性大)
  • 使用全局变量 (不推荐,容易在别的地方被改)
  • 静态数组(静态变量有自己的存储区,不在栈上分配空间)
  • 显式分配内存(记得释放阿,内存泄漏)
  • 把分配内存的任务留给调用者(推卸责任,不过方法很好)

阅读(808) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~