为什么使用宏 #define FREE_ARG char* 来获取由 malloc 分配的空闲内存(数值方法)
Why the use of the macro #define FREE_ARG char* for free memory alllocated by malloc (Numerical recipes)
我正在研究 Numerical Recipes 中的一些例程,但我不明白在实现中使用宏 #define FREE_ARG char* 来释放内存。这是一段代码:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#define NR_END 1
#define FREE_ARG char*
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) nrerror("allocation failure in vector()");
return v-nl+NR_END;
}
void free_vector(float *v, long nl, long nh)
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
\ ^
\ '----- why?
}
我的问题是:为什么要这样释放内存free((FREE_ARG) (v+nl-NR_END));?
这可能是一个非常糟糕的代码。注意
free()
采用参数类型 void *
。任何指针类型都可以隐式转换为 void *
,无需转换。
注:
这一行
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
转换也不是必需的,应该避免。 See this discussion on why not to cast the return value of malloc()
and family in C
.。这也是之前使用bad的原因之一。
我正在研究 Numerical Recipes 中的一些例程,但我不明白在实现中使用宏 #define FREE_ARG char* 来释放内存。这是一段代码:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#define NR_END 1
#define FREE_ARG char*
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) nrerror("allocation failure in vector()");
return v-nl+NR_END;
}
void free_vector(float *v, long nl, long nh)
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
\ ^
\ '----- why?
}
我的问题是:为什么要这样释放内存free((FREE_ARG) (v+nl-NR_END));?
这可能是一个非常糟糕的代码。注意
free()
采用参数类型 void *
。任何指针类型都可以隐式转换为 void *
,无需转换。
注:
这一行
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
转换也不是必需的,应该避免。 See this discussion on why not to cast the return value of malloc()
and family in C
.。这也是之前使用bad的原因之一。