문제
준수 (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");
NB : 컴파일하려면 다음을 사용합니다. 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;
}
다른 팁
사용중인 GCC 확장자와 동등한 표준은 없습니다.
매크로에서 코드 대신 함수 (C99를 사용하는 경우 인라인 함수조차도)를 사용하여 동등한 결과를 얻을 수 있습니다. 인수 중 하나가 '유형 이름'이기 때문에 그 기능을 호출하려면 매크로가 여전히 필요하며 기능을 전달할 수 없기 때문입니다.
기능 유형과이를 사용하는 매크로의 예시는 @pmg의 답변을 참조하십시오.
제휴하지 않습니다 StackOverflow