I'm trying to code a function to filter non-alphabetic characters from a string in C.
So inside the function wordFilter I initialize a char array in order to store there the filtered string and then assign it to the pointer so I can return it.
However, it turns out that whenever the function is executed after the first time, it seems that the char array "reference" still keeps the value it when the last execution was done. Is there a way to make the "reference" array to be empty every time at the beginning of the execution of the function.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char *wordFilter(char *string) {
char reference[strlen(string)];
int index = 0;
while (*string) {
if (isalpha(*string)) {
reference[index] = *string;
index++;
}
string++;
}
char *ptr = malloc(sizeof(char) * index);
ptr = reference;
return ptr;
}
int main() {
char input[256];
char *ptr = input;
char input2[256];
fgets(input, 256, stdin);
char reference[256];
for (int pos = 0; sscanf(ptr, "%s%n", input2, &pos) == 1; ptr += pos) {
printf("%s ", wordFilter(input2));
}
return 0;
}
The main problem is this line:
ptr = reference;That doesn't copy the characters ofreferenceintoptr. As Eugene pointed out, that line causes the variableptrto point to the stack-allocatedreferencearray, leaking the memory youmalloced.Here are the changes I recommend:
referencelikechar reference[strlen(string) + 1];to allow room for the terminating null.whileloop, null-terminatereferencelike this:reference[index] = '\0';mallocand copying the string, usestrdup(reference)to heap-allocate a duplicate ofreference, and then you can return what you get fromstrdup.