Henry
Henry

Reputation: 574

Why does this malloc cause segfault on my virtual machine?

I am trying to dynamically allocate memory for some integers and am getting a segfault. This code runs fine on native MacOS, but fails when I try to run it on my Ubuntu virtual machine? What's the difference?

Code

// 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;

Error

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.

Upvotes: 1

Views: 607

Answers (1)

Stargateur
Stargateur

Reputation: 26717

You didn't verify that malloc didn't fail:

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;

Virtual machine could not have enough ram I suppose.


Complete code:

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

Upvotes: 1

Related Questions