Share your repls and programming experiences

← Back to all posts
Sort and Search in C
h
LennyPhoenix (9)

Basic example of using the bubble sort and binary search algorithm in C.

Feel free to share any improvements you can think of!

UPDATE: Added Menu and Merge Sort algorithm

Comments
hotnewtop
DynamicSquid (4928)

Cool! I noticed something though.

One line 47, you have:

free(list)

But I don't think that's enough, because the list memory looks like this:

[3] [7] [12] [28] [34]
 ^
 |
int*

And calling free(list) does this:

[ ] [7] [12] [28] [34]
 ^
 |
free()

But you still have to deallocate the other list elements.

So I think you have to loop through the list and free each element.

LennyPhoenix (9)

@DynamicSquid If you look in list_generate you can see that list is allocated with calloc, meaning you only have to free the head pointer of the array.

If I tried to free each item in the list, like this:

for (int i = 0; i < LIST_SIZE; ++i)
    free(list + i);

We would get an error, as freeing the original pointer would free the whole list:

free(): invalid pointer
exited, aborted

The memory of the list actually looks more like this:

{ 3 7 12 28 34 }
  ^
  |
  int *
DynamicSquid (4928)

@LennyPhoenix Oh, interesting. But if you used malloc, then you would have to free each element individually right?

LennyPhoenix (9)

@DynamicSquid In the case of a linked list, then yes, however malloc would also only need you to run free on the head pointer in this case

DynamicSquid (4928)

@LennyPhoenix Oh, never knew that. Sorry if these are really dumb questions, I do C++, and I always think these two languages are very similar, but every time I find out that I'm wrong lol

LennyPhoenix (9)

@DynamicSquid Don't worry about it :D
C++ and C might have near identical syntax, but C++ has evolved drastically so many of the features are completely different now (it's no-longer just "C with classes").

DynamicSquid (4928)

@LennyPhoenix Yeah, I'm currently coding a lot more in C to try and learn it a lot more. But thanks for the help!

LennyPhoenix (9)

@DynamicSquid No problem, good luck with learning C!