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.
*defs[i]. Before doing that, you need to initializedefs[i]to point somewhere.