,无论如何,我不认为这是处理失败的好方法。 我的第二个想法:
malloc
我认为这看起来更好,因为它看起来很干净,但这是因为我只处理三个指针。如果我有更多的指针,那看起来不会很干净。
同时,我已经看到了一个出色的方法将指针投入了
void test(void) {
int *a, *b, *c;
a = malloc(sizeof(*a));
if (a == NULL)
return;
b = malloc(sizeof(*b));
if (b == NULL) {
free(a); /* since `a` has been `malloc`ed. */
return;
}
c = malloc(sizeof(*c));
if (c == NULL) {
free(a); // since `a` and `b` have
free(b); // been `malloc`ed.
return;
}
}
。但是,据我了解,这项技术需要malloc
我最后的度假胜地:
a = malloc(sizeof(*a));
b = malloc(sizeof(*b));
c = malloc(sizeof(*c));
if (a == NULL || b == NULL || c == NULL) {
free(a); // I've read that it's fine
free(b); // to `free` a NULL pointer.
free(c);
return;
}
您可以通过
uintptr_t
,因此不需要检查。
NULL
void *container;
container = malloc(sizeof(int) * 3);
if (container == NULL)
return;
a = getaddr(0);
b = getaddr(1);
c = getaddr(2);
// def: getaddr
static inline int *getaddr(void *base, int index) {
return base + (sizeof(int) * index);
}