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 = ∑
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 = ∑
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;
}
运行结果: