Hello All

i am trying to compile a simple code for the strtok but getting the error as

segmentation fault ( core dumped ) .. any help would be appreciated.

#include <stdio.h>
#include  <netinet/in.h>
#include <stdlib.h>
#include <string.h>

main()
{
	char *test="asim.nazeer.helo.me";
	char *rsl=strtok(test,".");	
	//while(1)
	//{	
		
		printf("%s",rsl);
	//}
		
}

It would appear that the memory space on which the string is stored is not modifiable. But that's not expert opinion, rather just from empirical testing. Can't memset the location, so therefore it's not modifiable. And strtok modifies the string you pass it.

You can just make test as an array.

it works with the simple array but i donot understand y its not working like this .. actually in my senario i am getting the data in the above format..so i m stuck in it ..

You just need to have it on real allocated memory. If you really want a pointer then strcpy it to a calloc'd pointer.

It would appear that the memory space on which the string is stored is not modifiable.

Correct. String literals are defined as read-only by the language, and strtok() modifies its argument.

i donot know what to do can u explain me by the help of code please.

i donot know what to do can u explain me by the help of code please.

You have no choice but to make sure the source string passed to strtok() is modifiable. That means either storing it initially in an array:

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

int main(void)
{
    char src[] = "asim.nazeer.helo.me";
    char *tok = strtok(src, ".");
    
    while (tok != NULL) {
        printf("'%s'\n", tok);
        tok = strtok(NULL, ".");
    }

    return 0;
}

Or making a copy if you don't control the string provided or need to retain the original string for any reason:

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

void foo(const char *s) // Assuming no control over s
{
    char *copy = malloc(strlen(s) + 1);
    char *tok;
    
    if (copy == NULL)
        return;
        
    strcpy(copy, s);
    
    for (tok = strtok(copy, "."); tok != NULL; tok = strtok(NULL, "."))
        printf("'%s'\n", tok);
}

int main(void)
{
    char *src = "asim.nazeer.helo.me";

    foo(src);

    return 0;
}

Thanx Alot for your help it works now and i got the point y i was getting the error :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.