Srinath Sureshkumar
Srinath Sureshkumar

Reputation: 169

the usage of strtok() in c shows warnings and returns segmentation fault(core dumped)

I am learning C string operations and was using strtok() function. My code ended up with warning and then output was segmentation fault.

Here is the source code (in file token3.c):

#include <stdio.h>
#include <string.h>
int main() {
    char str[] = "aa.bb.cc.dd.ee.ff";
    char *p;
    p = strtok(str, '.');
    while (p != NULL) {
        printf("%s\n", p);
        p = strtok(NULL, '.');
    }
    return 0;
}

Warnings during compilation:

token3.c: In function ‘main’:
token3.c:6:15: warning: passing argument 2 of ‘strtok’ makes pointer from integer without a cast [-Wint-conversion]
      p=strtok(str,'.');
                   ^~~
In file included from token3.c:2:0:
/usr/include/string.h:335:14: note: expected ‘const char * restrict’ but argument is of type ‘int’
extern char *strtok (char *__restrict __s, const char *__restrict __delim)
               ^~~~~~
token3.c:9:17: warning: passing argument 2 of ‘strtok’ makes pointer from integer without a cast [-Wint-conversion]
    p=strtok(NULL,'.');<br>
                  ^~~
In file included from token3.c:2:0:
/usr/include/string.h:335:14: note: expected ‘const char * restrict’
but argument is of type ‘int’
    extern char *strtok (char *__restrict __s, const char *__restrict __delim)
                                               ^~~~~~<

expected output:

aa
bb
cc
dd
ee
ff

actual output:

Segmentation fault(core dumped)

Upvotes: 1

Views: 471

Answers (2)

user3629249
user3629249

Reputation: 16540

the syntax for strtok() is:

char *strtok( char *str, const char *delim );

Notice that the second parameter is a char pointer, not a char, so the second parameter in each of the calls to strtok() should be wrapped in double quotes, not single quotes

After correcting the syntax and adding some spacing for readability, the resulting code is:

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


int main( void ) 
{
    char str[] = "aa.bb.cc.dd.ee.ff";
    char *p;
    p = strtok( str, "." );

    while( p ) 
    {
        printf( "%s\n", p );
        p = strtok( NULL, "." );
    }
    return 0;
}

and when running the corrected source code, the output is:

aa
bb
cc
dd
ee
ff

Note: with modern C compilers, the statement:

return 0;

can be eliminated as a return from main() (when not specifically stated otherwise) is 0

Upvotes: 3

Srinath Sureshkumar
Srinath Sureshkumar

Reputation: 169

That's was a mistake just replace

strtok(str,'.');

with

strtok(str,".");

The 2nd argument of strtok() is denotes the delimiters and expects the type

const char *

and so must be enclosed in " ".

Syntax of strtok()

char *strtok(char *str, const char *delim);

Upvotes: 3

Related Questions