1. 返回栈区地址
#include <stdio.h>
int *fun()
{
int a = 10;
return &a;
}
int main(int argc, char *argv[])
{
int *p = NULL;
p = fun();
*p = 100; // 操作野指针指向的内存,err
return 0;
}
2. 返回data区地址
#include <stdio.h>
int *fun()
{
static int a = 10;
return &a; // 函数调用完毕,a不释放
}
int main(int argc, char *argv[])
{
int *p = NULL;
p = func();
*p = 100; // ok
printf("*p = %d\n", *p);
return 0;
}
3. 值传递1
#include <stdio.h>
#include <stdlib.h>
void fun(int *tmp)
{
tmp = (int *)malloc(sizeof(int));
*tmp = 100;
}
int main(int argc, char *argc[])
{
int *p = NULL;
fun(p); // 值传递,形参修改不会影响实参
printf("*p = %d\n", *p);
return 0;
}
4. 值传递2
#include <stdio.h>
#include <stdlib.h>
void fun(int *tmp)
{
*tmp = 100;
}
int main(int argc, char *argv[])
{
int *p = NULL;
p = (int *)malloc(sizeof(int));
fun(p); //值传递
printf("*p = %d\n", *p); //ok,*p为100
return 0;
}
5. 返回堆区地址
#include <stdio.h>
#include <stdlib.h>
int *fun()
{
int *tmp = NULL;
tmp = (int *)malloc(sizeof(int));
*tmp = 100;
return tmp; // 返回堆区地址,函数调用完毕,不释放
}
int main(int argc, char *argv[])
{
int *p = NULL;
p = fun();
printf("*p = %d\n", *p);//ok
//堆区空间,使用完毕,手动释放
if( p != NULL)
{
free(p);
p = NULL;
}
return 0;
}