我需要三遍我需要三遍,如果其中一个呼叫失败,我想早点

问题描述 投票:0回答:0

,无论如何,我不认为这是处理失败的好方法。 我的第二个想法:

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

为0。
我最后的度假胜地:

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);
}
	

c malloc
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.