Munir
Munir

Reputation: 3612

Dynamic array of int pointers causing segmentation fault

I found a segmentation fault in my C code and could not find a good explanation or solution for it after searching.

This first code gives me segmentation fault after printing 0.

#include <stdlib.h>
#include <stdio.h>
int main() {
    int **defs = malloc(16 * sizeof *defs);
    int i;
    for (i = 0; i < 16; i++) {
        printf("%d\n", i);
        *defs[i] = i;
    }
    free(defs);
    return 0;
}

This second code works fine.

#include <stdlib.h>
#include <stdio.h>
int main() {
    int *defs = malloc(16 * sizeof defs);
    int i;
    for (i = 0; i < 16; i++) {
        printf("%d\n", i);
        defs[i] = i;
    }
    free(defs);
    return 0;
}

These are just examples, not my actual code. I also tried doing pointer arithmetic but same result. Could someone please explain this? Thank you.

Upvotes: 2

Views: 87

Answers (1)

Parnab Sanyal
Parnab Sanyal

Reputation: 739

In first code you have not allocated each of the int* memory blocks. So, before assigning values to defs[i], you have to populate it with memory of type int*.

defs[i] = (int*)malloc(sizeof(int) * number_of_elements);

And then defs[i][some_index] = value.

Upvotes: 4

Related Questions