user1820560
user1820560

Reputation: 27

C multiple files, segmentation fault printing an array

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.

Upvotes: 0

Views: 306

Answers (1)

Nikos C.
Nikos C.

Reputation: 51880

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);

Upvotes: 5

Related Questions