Jade Yui
Jade Yui

Reputation: 1

c Segmentation fault in macOS ; sometimes, and sometimes not

  void makeDouble(int **a, int *size){
    int i, j;
    *size *= 2;
    *a = (int *)realloc(*a, (*size)*sizeof(int));
    for(i=0; i<*size/2; i++){
        (*a)[*size/2+i] = (*a)[i] * 2;
    }

    int temp;
    for(i=0; i<*size-1; i++){
        for(j=0; j<*size-i-1; j++){
            if((*a)[j]>(*a)[j+1]){
                temp = (*a)[j];
                (*a)[j] = (*a)[j+1];
                (*a)[j+1] = temp;
            }
        }
    }
}

$ this is my code. What I wanted to do is getting a size and input as size, then making them all doubled, and sorting them.

But when I compile this, sometimes it collapses with segmentation fault and sometimes doesn't. And sometimes, it says "malloc: * error for object 0x7fda70c02730: incorrect checksum for freed object - object was probably modified after being freed. * set a breakpoint in malloc_error_break to debug Abort trap: 6" Why and What can I do with this? Sorry if my question is bad, I'm beginner with c.

Upvotes: 0

Views: 762

Answers (1)

nullp0tr
nullp0tr

Reputation: 485

First Segfault

One place where this would cause a segfault for sure is:

int size;
scanf("%d", &size);
int* a = (int *)malloc(size*sizeof(int));

if you pass it a character instead of a number that fits into an integer this would fail, because scanf is not gonna write to size.

You have to check the return of scanf which is the number of input items successfully matched:

if (scanf("%d", &size) != 1) {
    fprintf(stderr, "Supplied size is not a valid number.\n");
    return 1; 
}

Memory Leak

if realloc returns NULL because it failed to allocate enough space, you get a memory leak because you do:

int *a = realloc(a, ...);

This pattern is buggy, because assigning the return of realloc to the array you wanna reallocate means you lose the reference to the allocated array since a == NULL. Do:

int *temp = realloc(a, ...);
if (temp == NULL) {
    free(a); // Or continue using it ..
} else {
    a = temp;
}

Heap Corruption

Your function makeDouble is causing a heap corruption because you're accessing and modifying out of bound memory. I'm getting a realloc() abort: invalid next size with glibc, so you're most likely smashing the heap already allocated by the runtime, but not reaching the next page, hence no Segfault and a runtime error instead.

Upvotes: 1

Related Questions