0

I've written a code to remove special chars from string. But, getting the exception as written in the heading. Using VS2012.. Any solutions?

void remover(char *input)
{
int j = 0;
char *temp = (char *) malloc(sizeof(char)*strlen(input));
for(int i = 0 ; input[i] != '\0' ; i++)
{
    if(isalpha(input[i]) || isdigit(input[i]))
    {
        *temp[j] = *input[i];
        j++;
    }
}

*temp[j] = '\0';
for(j = 0 ; temp[j] != '\0' ; j++)
    *input[j] = *temp[j];   // exception here

*input[j] = '\0';
//free(temp);
}
  • I suspectn "input" might be a string literal. String literals are stored in read-only memory - you cannot modify them. Look here for more details: http://stackoverflow.com/questions/480555/modifying-c-string-constants – FoggyDay Apr 11 '14 at 07:38
  • solutions for that? even string copy wont work? – Vishal Sharma Apr 11 '14 at 07:42
  • Show the code that calls `remover`. – Jabberwocky Apr 11 '14 at 07:44
  • The "solution" is to copy into read-write memory, like you're doing with "temp". You just can't write from "temp" back into "input", if "input" happens to be a string constant! You *can* copy input into another variable (e.g. with strcpy), and pass that other variable input "remover()". – FoggyDay Apr 11 '14 at 07:45
  • okay got it!! i have atruct with *input and *output variable.. changed it to input[50] and output[50] it works now – Vishal Sharma Apr 11 '14 at 07:48
  • What possessed you to write `*(input+j)` instead of `input[j]`? – David Heffernan Apr 11 '14 at 07:58

1 Answers1

1

First, you need to add 1 in your malloc for the final '\0', but this is not your problem.

How are you testing it? You can't modify strings literals so remover("Test") will not be allowed and you should instead return the new string (temp) and have you caller decide when to free it or if it wants to free the original.

CMoi
  • 846
  • 4
  • 9