C语言中结构体内存free

  来自实训第三天的某段代码,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
struct vec2f {
float x;
float y;
};
typedef struct vec2f vec2f;

vec2f* vec2f_alloc() {
vec2f* ret;
ret = ( vec2f* ) malloc( sizeof( vec2f ) );
//if( !ret ) // if error occurs
return ret;
}

void vec2f_init( vec2f* v, float x, float y ) {
v->x = x;
v->y = y;
}

vec2f* vec2f_new( float x, float y ) {
vec2f* ret = vec2f_alloc();
vec2f_init( ret, x, y );
return ret;
}

void vec2f_delete( vec2f** v ) {
free( *v );
*v = NULL;
}

void vec2f_print( const vec2f* v ) {
printf( "[ %g %g ]\n", v->x, v->y );
}

  关于 vec2f_delete 函数参数为什么是 pointer to pointer???
  原因可能是,C 语言里面没有 引用 这个东西,上面释放内存的函数,除了将结构体那块内存释放外,为了避免 野指针 的情况,还需要将指向结构体那块内存的 pointer 置为 NULL。假如写成下面这种形式,

1
2
3
4
void vec2f_delete( vec2f* v ) {
free( v );
v = NULL;
}

  由于函数参数传递的临时拷贝,v = NULL; 只在函数作用域内有效,调用该函数并不能真正使 指向结构体那块内存的 pointer 失效,野指针 仍然存在!   

文章目录