Search code examples
cundefined-behaviorc-stringsstrtokstring-literals

why am I getting "Access violation" writing location?


I am trying to use strtok to get a string with \0 instead of spaces for replacing the \0 with # so I am using strtok for that. but I am getting - Access violation writing location in this line - char* word = strtok(stringOfNumberSign, delimiters);

char* addNumberSignToString(char* stringOfNumberSign)
{
    int numOfWords = 0;
    char* delimiters = " ";
    char* word = strtok(stringOfNumberSign, delimiters);
    while (word)
    {   
        numOfWords++;
        word = strtok(NULL, delimiters);
    }

    return stringOfNumberSign;
}

int main()

{
    char* stringForNumberSign = "welcome to hello world";
    char* result;
    result = addNumberSignToString(stringForNumberSign);
    printf("%s", result);
}

Solution

  • The function strtok changes the passed string.

    From the C Standard (7.23.5.8 The strtok function)

    4 The strtok function then searches from there for a character that is contained in the current separator string. If no such character is found, the current token extends to the end of the string pointed to by s1, and subsequent searches for a token will return a null pointer. If such a character is found, it is overwritten by a null character, which terminates the current token. The strtok function saves a pointer to the following character, from which the next search for a token will start.

    However you may not change a string literal. Any attempt to change a string literal results in undefined behavior.

    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.

    And you are trying to change a string literal

    char* stringForNumberSign = "welcome to hello world";
    //...
    result = addNumberSignToString(stringForNumberSign);
    

    At least you should use a character array instead of the string literal

    char stringForNumberSign[] = "welcome to hello world";
    

    Pay attention to that your function as is does not make a sense.