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.
asked Sep 20, 2016 at 4:32
Munir
3,6303 gold badges21 silver badges32 bronze badges
1 Answer 1
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.
answered Sep 20, 2016 at 4:45
Parnab Sanyal
7395 silver badges19 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Munir
In my case, adding
def[i] = malloc(sizeof(int)); in the loop worked. Thanks.Parnab Sanyal
your
def[i] can only store 1 element....But you can store more than 1 element. But what you should always avoid....segmentation fault can occur.Kyle Strand
@Munir ...um. Why are you allocating individual
ints on the heap, exactly? Why are you even creating an array of pointers instead of an array of ints, and why are you using malloc instead of new?Munir
@KyleStrand I don't know the initial size of the array. So I can't do it on the stack. I need the array of pointers because in my program, the data is read from a file and shared across the program. Also, this is C, not C++. So there is no
new or delete, only malloc and free.Kyle Strand
@Munir Ah, could have sworn I saw you including
iostream--sorry. But I don't understand what the relationship is between (1) keeping pointers rather than raw ints in your array, (2) reading data from a file, and (3) sharing data throughout the program. Those three issues seem entirely unrelated.lang-c
*defs[i]. Before doing that, you need to initializedefs[i]to point somewhere.