0

I have this code interaction with 2 files, but I am getting a segmentation error in these two functions and I need help figuring out why. fileA.c passes an int** to a function in fileB.c, the int** serves as an output parameter because I want to make an int array in fileB and have foo point to it so I can print it in fileA. In fileB.c, I make an array, and set the pointer to it.

size and foo are initialized in another function in a main file. It compiles fine, the output though would be (if size == 10) :

0 1 2 3 4 5 6 7 8 9

Segmentation fault

In fileA.c:

void testPointing(int size, int** foo) {
    initialize(size, foo);
    int i;
    for(i = 0; i < size; i++) {
        printf("%d ", (*foo)[i]);
    }
}

fileB.c:

void initialize(int size, int** foo) {
    int* a;
    a = (int*)malloc(size * sizeof(int);
    int i;
    for(int i = 0; i < size; i++) {
        printf("%d ", a[i]);
    }
    printf("\n\n");
    foo = &a;
}

I need help fixing and understanding why I am getting a segmentation fault. Whenever I opt to put the loop located in fileA.c after foo = &a in fileB.c instead, it compiles and shows a correct output.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • why are you printing a[i]? It is uninitiated memory. – UmNyobe Nov 26 '12 at 08:00
  • 1
    Also note that it's a [bad idea to cast the return value of `malloc()` in C](http://stackoverflow.com/a/605858/28169), so write the allocation like this: `a = malloc(size * sizeof *a);`. – unwind Nov 26 '12 at 08:03

1 Answers1

5

The address returned by malloc() is what holds your data, and that's stored in a, not &a. &a is just the address of the local variable a.

Also, foo is just the local function argument of initialize(), not the passed argument of the caller; that's *foo. That leaves the caller's foo unset, which is why you get a segmentation fault.

So instead of:

foo = &a;

you need:

*foo = a;

And the initial call to testPointing() should be something like this:

int* array;
testPointing(size, &array);
Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • Thank you for the clear explanation, everything works fine now. I understand my errors and the concepts needed to avoid it again, and I can continue to code the rest of my project. – user1820560 Nov 26 '12 at 08:23