我有以下代码:
void f(size_t n) {
int *a = malloc(n * sizeof *a);
if(a == NULL) {
report_error_and_exit();
}
int *b = malloc(n * sizeof *a);
if(b == NULL) {
free(a);
report_error_and_exit();
}
int *c = malloc(n * sizeof *a);
if(c == NULL) {
free(a);
free(b);
report_error_and_exit();
}
/*use a, b, c*/
}
Run Code Online (Sandbox Code Playgroud)
或类似的规定。基本上,我需要多个malloc,并且所有这些都不能失败。
我想知道我应该在哪里释放一些分配的内存。随着函数变得越来越长,检查malloc失败变得更加混乱。
我想到的一个可能的解决方案是执行如下操作:
void f(size_t n) {
int *a = malloc(n * sizeof *a);
if(a == NULL) {
goto malloc_fail;
}
/*...*/ …Run Code Online (Sandbox Code Playgroud) 假设我有代码:
int x = 5;
int* p = &x;
Run Code Online (Sandbox Code Playgroud)
然后写入*p将返回 5 并允许我修改x(如预期的那样)。说,无论出于何种原因,我然后写:
int y = p; // y holds x's address
*y = 3; // this is invalid and throws an error when compiling
*((int*)y) = 3; // this is okay
Run Code Online (Sandbox Code Playgroud)
(在 gcc 9.2 上编译时)
我的问题是:为什么 C 不允许我们*在非指针类型上使用?