Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the following C program give a bus error?

I think it's the very first strtok call that's failing. It's been a while since I've written C and I'm at a loss. Thanks very much.

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

int main(int argc, char **argv) {
  char *str = "one|two|three";

  char *tok = strtok(str, "|");

  while (tok != NULL) {
    printf("%s\n", tok);
    tok = strtok(NULL, "|");
  }

  return 0;
}
like image 967
nc. Avatar asked Dec 18 '10 22:12

nc.


2 Answers

String literals should be assigned to a const char*, as modifying them is undefined behaviour. I'm pretty sure that strtok modifies it's argument, which would explain the bad things that you see.

like image 71
Puppy Avatar answered Sep 18 '22 11:09

Puppy


There are 2 problems:

  1. Make str of type char[]. GCC gives the warning foo.cpp:5: warning: deprecated conversion from string constant to ‘char*’ which indicates this is a problematic line.

  2. Your second strtok() call should have NULL as its first argument. See the docs.

The resulting working code is:

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

int main(int argc, char **argv) {
  char str[] = "one|two|three";

  char *tok = strtok(str, "|");

  while (tok != NULL) {
    printf("%s\n", tok);
    tok = strtok(NULL, "|");
  }

  return 0;
}

which outputs

one
two
three
like image 38
moinudin Avatar answered Sep 21 '22 11:09

moinudin