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.

2
  • why are you printing a[i]? It is uninitiated memory. Commented Nov 26, 2012 at 8:00
  • 1
    Also note that it's a bad idea to cast the return value of malloc() in C, so write the allocation like this: a = malloc(size * sizeof *a);. Commented Nov 26, 2012 at 8:03

1 Answer 1

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

1 Comment

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.

Your Answer

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.