-4

I looked around and I could not find a solution of my problems in other question. For some reason, then I get segmentation fault when I run my program and it seems to be because i am changing the give string. I tried passing a pointer to a char pointer and edit that, but to no avail.

what I get:

before: juanpablo Segmentation fault (core dumped)

My code:

void rm_char(char* word, int pos){

   printf("before: %s\n", word);

   int len = strlen(word);

   int i;

   i = pos;

   while(word[i+1] != '\0'){

     word[i] = word[i+1];

     i++;
   } 

   word[i] = '\0';

   printf("after: %s\n", word);
} 


int main(void){

   rm_char("juanpablo", 2);

}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • The only duty of the compiler - is to compile the code. If it is doing it, the rest is about the code itself. – Eugene Sh. Dec 06 '17 at 18:24

1 Answers1

0

From the C Standard (6.4.5 String literals)

7 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.

To escape the error you could call the function like

char s[] = "juanpablo";   

rm_char( s, 2 );

Take into account that it is better to use type size_t instead of the type int for the second parameter and the variable len declared like

int len = strlen(word);

is not used in the function.

The function should be declared like

char * rm_char(char* word, size_t pos);

Here is a demonstrative program

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

char * rm_char(char *word, size_t pos)
{
    size_t n = strlen( word );

    if ( pos < n )
    {
        //memmove( word + pos, word + pos + 1, n - pos );
        do 
        {
            word[pos] = word[pos+1];
        } while ( word[pos++] );
    }

    return word;
}

int main(void) 
{
    char word[] = "juanpablo";

    puts( word );
    puts( rm_char( word, 2 ) );

    return 0;
}

Its output is

juanpablo
junpablo
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • So, let me see if i understand, if a make string using malloc() and strcpy(), it is impossible to edit it because it is a string literal. Or it is is because I passed a string in double quotes, "string literal" that i'm unable to edit it? – Telegonicaxx Dec 06 '17 at 18:35
  • @Telegonicaxx You passed to the function a pointer to the first character of a string literal and using this pointer you are trying to change the string literal within the function. – Vlad from Moscow Dec 06 '17 at 18:37
  • thanks you @Vlad from Moscow! I was really scratching my head with this one. – Telegonicaxx Dec 06 '17 at 18:38