函数调用的过程是什么 ,希望给我讲解一下
在主函数中调用子函数,那么在子函数调用的过程中,有动态开辟空间的语句,在函数调用结束后这些动态开辟的空间是不是就自动释放了,还是还在保留着;
2015-04-08 21:09

2015-04-08 21:38
2015-04-08 21:50
程序代码:/* 在主函数中开辟空间 在子函数里改变动态空间
[color=#0000FF]#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define FREE(p) free(p), p = NULL
const char str[] = "0123456789";
void foo(char *ptr) {
realloc(ptr, 10 * sizeof(char));
strncpy(ptr, str, 10);
ptr[9] = 0;
FREE(ptr);
}
int main(void) {
char p = malloc(5 * sizeof(char));
foo(p);
//若是子函数里FREE执行了
//则p在子函数中已经释放了
//由于函数是值传递的 p的值没有改变
//下面语句中 puts被执行 结果是错误的
//想得正确结果 注释掉子函数中的FREE
if(p) puts(p);
FREE(p); //程序结束前 两个FREE之中一个被执行 就不会泄漏
return 0;
}
[/color]*/
//以上做法不推荐
//下面利用指针的指针来传值 改变动态空间大小和值
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define FREE(p) free(p), p = NULL
const char str[] = "0123456789";
void foo(char **p2) {
realloc(*p2, 10 * sizeof(char));
strncpy(*p2, str, 10);
(*p2)[9] = 0;
//FREE(*p2); //此行注释 主函数里的puts就能正确执行
}
int main(void) {
char *p1 = malloc(5 * sizeof(char));
foo(&p1);
if(p1) puts(p1);
FREE(p1);
return 0;
}

2015-04-08 22:35
2015-04-08 23:12
程序代码:#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define FREE(p) free(p), p = NULL
const char str[] = "0123456789";
void foo(char **ptr) {
*ptr = realloc(*ptr, 10 * sizeof(char));
strncpy(*ptr, str, 10);
(*ptr)[9] = 0;
//FREE(*ptr);
}
int main(void) {
char *p = malloc(5 * sizeof(char));
foo(&p);
if(p) puts(p);
FREE(p);
return 0;
}

2015-04-08 23:41
程序代码:#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define FREE(p) free(p), p = NULL
const char str[] = "0123456789";
char *p = NULL;
void foo(void) {
p = realloc(p, 10 * sizeof(char));
strncpy(p, str, 10);
p[9] = 0;
//FREE(p);
}
int main(void) {
p = malloc(5 * sizeof(char));
strncpy(p, str, 5);
p[4] = 0;
puts(p);
foo();
if(p) puts(p);
FREE(p);
return 0;
}

2015-04-08 23:47
2015-04-08 23:55
2015-04-09 00:00