given this posted code:
tmp = (t_dico *)malloc(sizeof(t_dico));
y = 0;
while (dico[y])
{
if (dico[y + 1] && ft_strcmp(dico[y]->key, dico[y + 1]->key) > 0)
{
tmp = dico[y];
dico[y] = dico[y + 1];
dico[y + 1] = tmp;
y = -1;
}
y++;
}
free(tmp);
the tmp
initially gets a pointer to some allocated memory, via the call to malloc()
Then this line overlays that pointer:
tmp = dico[y];
the result is a memory leak
Then the code passes a pointer to one of the elements in the dico
array
(the one from dico[y]
) to the free()
function.
to correct this, remove the statement that calls malloc()
and remove the statement that calls free()
.
BTW: this sort algorithm does not actually perform the desired sort.
Suggest implementing a bubble
or insertion
or selection
sort.
here is the algorithm for a selection
sort.
Where 'n' is number of entries in array[]
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
position = c;
for ( d = c + 1 ; d < n ; d++ )
{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
temp = array[c];
array[c] = array[position];
array[position] = temp;
}
}