-6

i'm getting segmentation fault core dumped when im using strtok at the next code part. the code is getting debugged but when I run it I get the segmentation fault. How can I fix it?

struct{ char *name;
void(*func)(void);
}cmd[]={
{"read_cm",read_cm},
{"NA",NULL}
};
int d;
char *s="_\n";
  char *token2;
  for(d=0;cmd[d].func!=NULL;d++)
   {
   token2=strtok((cmd[d].name),s);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Esmo
  • 1
  • 1
  • Welcome to Stack Overflow! _Questions seeking debugging help (why isn't this code working?) must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]._ – Sourav Ghosh Jun 01 '17 at 12:19
  • When you create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve), please make sure it actually *compiles*. – Some programmer dude Jun 01 '17 at 12:19
  • Please format your code correctly. – Jabberwocky Jun 01 '17 at 12:19
  • Also please use a debugger to locate where the crash happens in your code, and check the values of all involved variables when the crash happens. Make sure they are valid. And if you still can't figure it out, then include all that information in your question. – Some programmer dude Jun 01 '17 at 12:20
  • `cmd[d]name` is invalid syntax, you're missing a `.`. – Barmar Jun 01 '17 at 12:20

1 Answers1

3

You may not modify a string literal. Any attempt to modify a string literal results in undefined behavior.

The standard C function strtok tries to insert a terminating zero while splitting a string into substrings.

To resolve the problem use a character array instead of the pointer name. Or allocate memory dynamically and copy a string to the allocated memory pointed to by the pointer name.

For example

struct
{ 
    char name[8];
    void(*func)(void);
} cmd[] = 
{
    { "read_cm", read_cm },
    { "NA", NULL }
};

Another approach is to use standard C functions strcspn and strspn instead of strtok to find substrings.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335