Domanda

so i have this function that is supposed to sort some array, but it leaks too much memory causeing my program to crash. I tried to malloc and free char "tempwordy" but it doesn't work, there are still some leaks (2700 unfreed allocs at the end) and I can't find them :( Help?

void quick_sort(int low,int high)
{
    int pivot,j,temp,i;
    char *tempwordy=malloc(40*(sizeof(char)));

    if(low<high)
    {
        pivot=low;
        i=low;
        j=high;

        while(i<j)
        {
            while((counters[i]<=counters[pivot])&&(i<high))
            {     
                i++;
            }

            while(counters[j]>counters[pivot])
            {
                j--;
            }

            if(i<j)
            { 
                temp=counters[i];
                counters[i]=counters[j];
                counters[j]=temp;

                strcpy(tempwordy,words[i]);
                strcpy(words[i],words[j]);
                strcpy(words[j],tempwordy);
            }
        }
printf("zav");
    temp=counters[pivot];
    counters[pivot]=counters[j];
    counters[j]=temp;

    strcpy(tempwordy,words[pivot]);
    strcpy(words[pivot],words[j]);
    strcpy(words[j],tempwordy); 



    quick_sort(low,j-1);
    quick_sort(j+1,high);

    free(tempwordy);
    }
}
È stato utile?

Soluzione 2

Your free() call is inside your if() statement. Here is a reduced version of your code just showing the memory allocation. Move your free() call to after the if() closes:

void quick_sort(int low,int high)
{
    char *tempwordy=malloc(40*(sizeof(char)));
    if(low<high)
    {
       free(tempwordy);
    }
}

Altri suggerimenti

The "free" is inside the "if" block, so it's not executed when "low>=high". That's why at the end some blocks are still allocated

If you feel you MUST use malloc/free (but don't have to, actually), then do malloc inside if, and do free before recursive calls of quick_sort. That will not make your program good, but will make it better.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top