Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's wrong with my clean function?

Tags:

c

I want to write a function clearing any string from numbers and signs like !@#$%^&*()_+ but always I get this error: * glibc detected ./clear: invalid fastbin entry (free): 0x0000000001d29490 **

Here's the code:

void clean(char *dirty)
{
    int i = 0, j = 0;
    char *temp;

    temp = strdup(dirty);
    while(i < strlen(temp))
    {
        if(isalpha(temp[i]) && isspace(temp[i]))
        {
            dirty[j] = temp[i];
            j++;
        }
        i++;
    }
    dirty[j] = '\0';
    free(temp);
}
like image 334
all0star Avatar asked Dec 11 '25 05:12

all0star


1 Answers

You should check for the return value of strdup. If the memory allocation encountered problems (e.g. not enough memory), temp gets the value NULL. Check if that is the case and exit with an error message.


Your if statement is always false:

if(isalpha(temp[i]) && isspace(temp[i]))

How could temp[i] be both alphanumerical and space?


Note also (although it's not the question) that this is rather a job for for than while (looping through all elements of an array until its end). It's always good to use the expected idiom.

This could also be done in place (no need for a temp string):

dirty[j] = dirty[i];

since i is greater or equal to j.

like image 81
Gauthier Avatar answered Dec 13 '25 19:12

Gauthier