为什么这个malloc会导致我的虚拟机出现段错误?

时间:2018-04-13 15:30:51

标签: c int malloc ubuntu-16.04

我正在尝试为某些整数动态分配内存,并且遇到了段错误。这段代码在原生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.

1 个答案:

答案 0 :(得分:1)

您没有确认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 fail\n");
        goto a;
    }
    int *b = malloc(sizeof *b);
    if (!b) {
        fprintf(stderr, "b allocation fail\n");
        goto b;
    }
    int *c = malloc(sizeof *c);
    if (!c) {
        fprintf(stderr, "c allocation fail\n");
        goto c;
    }
    int *d = malloc(sizeof *d);
    if (!d) {
        fprintf(stderr, "d allocation fail\n");
        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;
}