0

here is my code,

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

main ()
{
    explode (" ", "this is a text");
}

    explode (char *delimiter, char string[])
{
char *pch;
printf ("Splitting string \"%s\" into tokens:\n",string);
pch = strtok (string,delimiter);
while (pch != NULL)
{
    printf ("%s\n",pch);
    pch = strtok (NULL, delimiter);
}
return 0;
}

I compile this code using gcc -o 1.exe 1.c and shows no error. But when i execute 1.exe it shows Splitting string "this is a text" into tokens: and at that moment 1.exe stops working (a dialogue box of windows shows). can anybody tell the problem and solve the problem? I am using windows 10.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Masum Nishat
  • 167
  • 3
  • 15

2 Answers2

2

In your explode() function, you're passing a string liteal ("this is a text") and using the same as the input to strtok().

As strtok() modifies the input string, here, it will invoke invokes undefined behavior. As mentioned in th C11 standard, chapter §6.4.5, String literals

[...] If the program attempts to modify such an array, the behavior is undefined.

You can either

  • Define an array and initalize it with the string literal and the use the array as input to strtok().
  • take a pointer, use strdup() to copy the initializer and then supply that pointer to strtok().

The bottom line is, the input string to strtok() should be modifiable.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

While you can't do this with strtok because the literal can't be modified, it can be done with strcspn.

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

void explode (char *delimiter, char *string);

int main()
{
    explode (" ", "this is a text");
    return 0;
}

void explode (char *delimiter, char *string)
{
    int span = 0;
    int offset = 0;
    int length = 0;

    if ( delimiter && string) {
        length = strlen ( string);
        printf ("Splitting string \"%s\" into tokens:\n",string);
        while (offset < length) {
            span = strcspn ( &string[offset],delimiter);//work from offset to find next delimiter
            printf ("%.*s\n",span, &string[offset]);//print span number of characters
            offset += span + 1;// increment offset by span and one characters
        }
    }
}
user3121023
  • 8,181
  • 5
  • 18
  • 16