top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Getting segmentation fault with strtok in C?

0 votes
693 views

Following is my code and getting segmentation fault. Please help

#include<stdio.h>
#include<string.h>
main()
{
    char *p,str[100]="Hi, How Are You, Fine, Thank You";
    p=strtok(str,",");
    printf("%s\n",p);
    while(p != NULL)
    {
        p=strtok(NULL,",");
        printf("%s\n",p);
    }
}

O/p is:
Hi
How Are You
Fine
Thank You
and then Segmentation fault.

posted Jun 19, 2015 by Chirag Gangdev

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Here is the tested code

#include<stdio.h>
#include<string.h>
main()
{
    char *p,str[100]="Hi, How Are You, Fine, Thank You";
    p=strtok(str,",");
    while(p != NULL)
    {
        printf("%s\n",p);
        p=strtok(NULL,",");
    }
}

in the last statement when strtok returns null you can not print a null.

answer Jun 19, 2015 by Salil Agrawal
Similar Questions
+4 votes

I have written print("%s", __LINE__); I get crashed. Can someone please explain why it is happened ?

0 votes

How can we debug the segmentation fault in a program which has been compiled without "-g" option?

+2 votes

I am writing the code without main function.

#include<stdio.h>
_start()
{
int a=10,b=20,res;
res=a+b;
printf("Res = %d\n",res);
}

Compiling : cc -nostartfiles filename.c

Output:

Res = 30
Segfault
...