2

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
2
  • 2
    *defs[i]. Before doing that, you need to initializedefs[i] to point somewhere. Commented Sep 20, 2016 at 4:36
  • 1
    Pointers must point somewhere before being dereferenced Commented Sep 20, 2016 at 4:40

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

5 Comments

In my case, adding def[i] = malloc(sizeof(int)); in the loop worked. Thanks.
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.
@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?
@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.
@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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.