0

I have written a method in C that removes characters from a string

char* removeChars(char input[], char remove[]) 
{
    int src, dst = 0;
    int size = strlen(input);
    bool flags[128];

    char output[18]; // <- This should be output[size]!

    int i;
    for(i=0; i<128; i++) {
        flags[i] = false;
    }

    int j=0;
    while(remove[j] != '\0') {
        flags[remove[j]] = true;
        j++;
    }

    for(src=0; src<size; src++) {
        if(flags[input[src]] != true) {
            output[dst++] = input[src];
        }
    }
    return output;
}

One of the issues that I am having is that when I attempt to set the size of the output array using size (i.e. char output[size]), The output array appears to always have zero elements. It only seems to work when I specify a specific size (like 18). Should I be using strcpy or malloc instead? If so, how should it be done?

1
  • The program only appears to work when you compile with a constant instead of a variable. The scope of output is local to the removeChars function. Once the function returns, there is no requirement to keep that memory saved. The use of malloc for C is how the memory should be allocated and as indicated below, you need to free the memory before the end of execution or you will have a memory leak. Commented Nov 27, 2014 at 19:56

2 Answers 2

2
char *output = malloc(sizeof(char) * (size+1));

If you want memory to be dynamically allocated using size. Once you are done using this memory please free it.

free(output);
Sign up to request clarification or add additional context in comments.

1 Comment

Make that size+1 to account for the terminating NUL ('\0') character, and don't forget to free() the result of malloc().
1

Your program has undefined behaviour because you are returning pointer to the first element of a local array that in general case will be destroyed after exiting the function.

So you have to allocate the array in the heap dynamically.

The other problem is that you do not append the output string with the terminating zero.

The function woild look simpler if you would remove characters in the source string that is "in place". In this case there is no any need in an additional array.

Also you could use standard function strchr declared in header <string.h> that to determine whether a given character in the source string is present in the string that contains characters to be removed.

1 Comment

This was more of a programming exercise, so using strchr is not the purpose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.