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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With