-2

I'm writing a little programme to remove a word from a string. C segfaults in the for-loop inside the removeWord function (the third printf is never executed). What can the reason be? I'm an absolute newbee in C. When I try to print str[j] as %s inside the for loop, the compiler complains about str being an integer, not a string. Why is that?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void removeWord(char * str, char * toRemove)
{
    int i, j, k, stringLen, toRemoveLen;
    stringLen   = strlen(str);      // Length of string
    toRemoveLen = strlen(toRemove); // Length of word to remove
// ...(code for finding the word)...
        printf ("str='%s' StrLen=%d ToRem=%d i=%d j=%d\n",str, stringLen, toRemoveLen, i, j);
        for(j=i; j<=stringLen - toRemoveLen; j++)
        {
            printf ("j=%d\n", j);
            str[j] = str[j + toRemoveLen];
        }
        printf ("i=%d j=%d\n", i, j);
}

int main(void)
{
    char * term = "from the ";
    removeWord(term, "from");
    return 0;
}

1 Answers1

0

It's string literal. You can't modify it. As a result you get a segfault trying to modify it.(Actually it's undefined behavior).

What you can do is

char  term[] = "from the ";

that will help you modify it, which is what you want.

Even you can take a char* and allocate memory in it and copy the string but that's an overkill for this task.

From the standard it can be quoted that §6.4.5

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

In your case temp basically holds the address of the string literal which is non-modifiable. If you copy it and then that will be modifiable.

user2736738
  • 30,591
  • 5
  • 42
  • 56