如何以兼容(ISO C99)的方式执行以下操作?
#define MALLOC(type, length, message) ({ \
type * a_##__LINE__ = (type *)malloc((length) * sizeof(type)); \
assert(message && (a_##__LINE__ != NULL)); \
a_##__LINE__; \
})
double **matrix = MALLOC(double *, height, "Failed to reserve");
Run Code Online (Sandbox Code Playgroud)
注意:要编译,我使用:gcc -std = c99 -pedantic ...
您不应将测试malloc()放在assert():在进行发行版本构建时不会将其编译。我没有assert()在以下程序中使用过。
#include <stdio.h>
#include <stdlib.h>
void *mymalloc(size_t siz, size_t length,
const char *message, const char *f, int l) {
void *x = malloc(siz * length);
if (x == NULL) {
fprintf(stderr, "a.out: %s:%d: MALLOC: "
"Assertion `\"%s\" && x != ((void *)0)' failed.\n",
f, l, message);
fprintf(stderr, "Aborted\n");
exit(EXIT_FAILURE);
}
return x;
}
#define MALLOC(type, length, message)\
mymalloc(sizeof (type), length, message, __FILE__, __LINE__);
int main(void) {
int height = 100;
double **matrix = MALLOC(double *, height, "Failed to reserve");
/* work; */
free(matrix);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
没有与您使用的GCC扩展等效的标准。
您可以使用函数(如果使用的是C99,甚至可以使用内联函数)代替宏中的代码来获得等效的结果。您仍然需要一个宏来调用该函数,因为参数之一是“类型名”,并且您不能将其传递给函数。
有关函数类型和使用它的宏的说明,请参见@pmg的答案。