Home > front end >  Access violation In C Trying to Use strtok in a function
Access violation In C Trying to Use strtok in a function

Time:01-25

I am trying to pass a string to a function and tokenize the string, but it gives me an access violation error when it tries to execute strtok.

int main(void) {
char String1[100];
// note: I read data into the string from a text file, but I'm not showing the code for it here
tokenize(String1);

return 0;
}

void tokenize(char data[]) {
    strtok(data, ','); // gives me an access violation error
}

When I used strtok in main, it works, but not when I pass it to the function.

CodePudding user response:

You should consult man strtok for more detail. And it's advisable to use strtok_r instead of strtok.

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

void tokenize(char data[]) {
  char *token = data;
  while (1) {
    token = strtok(token, ",");
    if (!token) {
      break;
    }
    printf("token : %s\n", token);
    token = NULL;
  }
}
int main(void) {
  char String1[] = "a,b,c,d,e,f,g";
  // note: I read data into the string from a text file, but I'm not showing the
  // code for it here
  tokenize(String1);

  return 0;
}

CodePudding user response:

If your compiler is not giving you plenty of warnings about this code, please enable more warnings.

  1. You need to #include <string.h> to get the prototype for strtok().
  2. You either need a prototype for tokenize(), or more simply, just move its definition above main().
  3. (Where your actual bug is) The second parameter of strtok() should be a char *, not a char. So change ',' to ",".
  • Related