我正在尝试为某些整数动态分配内存,但出现段错误。此代码在本机 MacOS 上运行良好,但当我尝试在我的 Ubuntu 虚拟机上运行它时失败?有什么区别?
法典
// Create stuff to add
int* a = malloc(sizeof(int));
int* b = malloc(sizeof(int));
int* c = malloc(sizeof(int));
int* d = malloc(sizeof(int));
*a = 0;
*b = 1;
*c = 2;
*d = 3;
错误
Breakpoint 1, test_add_4_and_check () at test.c:125
125 int* a = malloc(sizeof(int));
(gdb) n
126 int* b = malloc(sizeof(int));
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a8b48a in malloc_consolidate (
av=av@entry=0x7ffff7dd1b20 <main_arena>) at malloc.c:4175
4175 malloc.c: No such file or directory.
您没有验证 malloc 没有失败:
int *a = malloc(sizeof *a);
int *b = malloc(sizeof *b);
int *c = malloc(sizeof *c);
int *d = malloc(sizeof *d);
if (!a || !b || !c || !d) {
exit(EXIT_FAILURE);
}
*a = 0;
*b = 1;
*c = 2;
*d = 3;
我想虚拟机没有足够的内存。
完整代码:
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int *a = malloc(sizeof *a);
if (!a) {
fprintf(stderr, "a allocation failn");
goto a;
}
int *b = malloc(sizeof *b);
if (!b) {
fprintf(stderr, "b allocation failn");
goto b;
}
int *c = malloc(sizeof *c);
if (!c) {
fprintf(stderr, "c allocation failn");
goto c;
}
int *d = malloc(sizeof *d);
if (!d) {
fprintf(stderr, "d allocation failn");
goto d;
}
*a = 0;
*b = 1;
*c = 2;
*d = 3;
free(d);
free(c);
free(b);
free(a);
return EXIT_SUCCESS;
d:
free(c);
c:
free(b);
b:
free(a);
a:
return EXIT_FAILURE;
}