1

First few parts of code:

    typedef struct
    {
        double sr, med;
        int **t;
    }wynik;

    wynik calc(int *t[], int size)
    {
        int i, *niep = NULL, j = 0, k = 1, sum = 0;
        int *sorted = (int*)malloc(size*sizeof(int));
        wynik out;
        //coping, sorting
        for (i = 0; i < size; i++)
            sorted[i] = (*t)[i];
        qsort(sorted, size, sizeof (**t), cmp);
        out.t = &sorted;
...
    return out;
    }

then in main():

wynik get = calc(&tab, tab_size);

Using debugger I discovered that in calc() out.t points to an array, but in main() get.t points to some weird things. How to fix it?

2
  • 1
    Your sturcture doesn't contain an array. It contains a pointer. Commented Mar 10, 2015 at 14:27
  • I'm sorry but nothing in this code makes any sense. It would seem you are uncertain about how pointers and arrays work and have therefore obfuscated your program to the point where you no longer know what it does. On top of that you have memory leaks. This code is unsalvageable. Commented Mar 10, 2015 at 14:34

1 Answer 1

3

out.t contains the address of the local variable sorted. When the function returns, this address is no longer valid because the local variable went out of scope.

I see no reason here that out.t should be int** instead of int*. If you change it to be int* and just set its value with out.t = sorted, it should work correctly.

Sign up to request clarification or add additional context in comments.

3 Comments

because he allocated the memory on the heap inside the function, that address should stay valid until it is freed, shouldn't it ?
@MattKo The address stored inside sorted (which was allocated by malloc) remains valid until freed. But the address of sorted itself (&sorted) becomes invalid when returning.
You're right, I got a bit distracted, this code is not so easy to analyze. Of course, the address of sorted is on the stack, but its content on the heap.

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.