*EDIT-I know strtok doesn't actually 'return' a segfault-I realize after submitting topic that is poor wording.

Hello,

I am having a problem with the C function strtok, as follows:

void function_name (char * cmd) /* Gathered from another function using readline.  Assume 'ls -l' in this example */
{
char *pch = NULL;
/* Other variable declarations */
printf ("%s\n", cmd); /* correctly prints 'ls -l' */
printf ("Before call to strtok\n");
pch = strtok (cmd, " ");
printf ("After call to strtok\n"); /* This line never prints due to segfault */
}

I am attempting to parse the 'ls -l' to pass to function execlp() or similar functions-I am required by constraints of assignment to get data via readline.

Thank you for any help can provide.

Edited 6 Years Ago by ItecKid: n/a

Try something like below

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

void mycall(char cmd[])
{
	char *pch = NULL;

	printf ("%s\n", cmd); /* correctly prints 'ls -l' */
	printf ("Before call to strtok\n");
	pch = strtok (cmd, " ");
	printf ("After call to strtok\n"); 
}

int main()
{

	char cmd[] = "ls -l";
	mycall(cmd);
	exit(EXIT_SUCCESS);
}

Well-I thank you for your reply-turns out my code was correct-my problem turns out to be a statement like

int i, j = 0;

does not work in C, which caused an odd value for i, causing a loop not to initiate. Strange, though, that this would cause the program to die where it did.

Marking solved.

I am not so sure if that was the only reason for your problem . Try running this piece of code

int main()
{
    char *arr = "ls -l";
    char *pch = NULL;
    
    printf("%s\n",arr);
    pch = strtok(arr," ");
    printf("%s\n",pch);

    return 0;
}

This will give you a seg fault. The reason being when you write
char *arr the memory for this is in the code segment of the program. You are not allowed to modify anything that is written in the code segement
When you issue the strtok command, you are telling the program to replace each instance of " " with '\0' or in other words you are modifying data written in the code segment.
The system does not like this and hence crashes on you

This question has already been answered. Start a new discussion instead.