pointer being freed was not allocated

Dec 3, 2012 at 2:11pm
I'm having trouble with memory management in a recursive function. I'm trying to implement quicksort in C, and the function worked just fine until I decided to free up memory. The problem is here:

1
2
3
4
5
6
7
8
9
10
int *smaller_s = quicksort(smaller_c, s_index);
int *larger_s = quicksort(larger_c, l_index);

free(smaller_c);
free(larger_c);

... concatenate stuff

free(smaller_s);
free(larger_s);


It is the last two free's that are causing the compiler to print the error in the title. I'm guessing it is because they weren't malloc'ed in the function call itself, but in the "previous" recursive call. Yet, this should be doable right?

Thanks,
Fafner
Dec 3, 2012 at 2:49pm
You cannot free stuff that has already been freed. Those pointers no longer point to a valid memory location when you try to free them the second time.
Dec 3, 2012 at 3:37pm
But they havent already been freed, though. smaller_s is made by sorting smaller_c, then smaller_c is freed, and after doing some other stuff smaller_s is freed.
Dec 3, 2012 at 4:49pm
how was was smaller_s allocated inside quicksort?
Dec 3, 2012 at 5:19pm
But they havent already been freed, though. smaller_s is made by sorting smaller_c, then smaller_c is freed, and after doing some other stuff smaller_s is freed.


My bad. I didn't notice your identifiers only differ by one letter. I'm having a hard time figuring out why quicksort would allocate and return memory.
Dec 3, 2012 at 10:01pm
Peter87, smaller_s is the output from quicksort, and the code is:

 
int *output = (int*)malloc(sizeof(int)*length);


cire: I realize I should have made the distinction clear :) Anyway, I'm allocating memory for the "largerThan"-array and "lessThanOrEqual"-array, and for the output array which contains the concatenation of those arrays. I can post the entire code if you want
Topic archived. No new replies allowed.