0

I run this code and core dumped...

#include <string.h>
#include <stdio.h>
int main()
{
    char *a= "ls";
    char *b= "ls -l";
    char *t = strtok(b," \t");
    if (!strcmp(a,t))
        printf("EQU\n");
    else
        printf("NOT EQU\n");
}

But after I change char *b="ls -l"; to char b[]="ls -l", it works.

Why?

I know that One is an array, and the other is a pointer. But are they different for strtok? And the manual page for strtok says that the first argument should be a char*.

xmc
  • 51
  • 1
  • 2

3 Answers3

1

From the man page, strtok modifies its first element.

When you initialize a char* with a literal string, you are pointing into the read-only memory that the literal was allocated in.

When you initialize a char[] with a literal string, it gets its own private memory, which is writeable.

Thus, you core dump on the first one but not the second one.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
1

strtok modifies the input string. It overwrites instances of the delimiter characters with null bytes in order to split the string up into null-terminated strings for each token. String literals are compiled into the program and typically reside in read-only segments of memory. As such, they can't be modified, and attempting to do so will result in a crash.

You could just modify your code to store the string on the stack as you've done:

char b[] = "ls -l";

Or create a temporary copy of the string:

char *str = strdup(b);
free(str);
jspcal
  • 50,847
  • 7
  • 72
  • 76
1

The manual if the function char * strtok ( char * str, const char * delimiters );:

str

C string to truncate.

Notice that this string is modified by being broken into smaller strings (tokens).

Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.

It tries to modify the const string literal char *b= "ls -l"; that is located in the read only memory and the program core dumped. When you modify the variable declaration to char b[]= "ls -l";, the string is located on the stack of main, data on stack can be modified.

Community
  • 1
  • 1
273K
  • 29,503
  • 10
  • 41
  • 64