0

please tell me why this code give me segmentation fault?
I want to split the command into tokens but I don't know why it give me segmentation fault!!

char command[500]="asdadas asdasdas asdadas";   
int i,j,k;
char tokens[4][200];

for(i=0,j=0,k=0;  i<strlen(command);  i++)
{
    if(command[i]==' ') 
    {
        tokens[j][k]='\0';
        k=0;
        j++;
        continue;
    }

    tokens[j][k]=command[i];
    k++;
}
tokens[j][k]='\0';
9
  • 2
    Splitting a string into tokens is strtok's whole purpose for existence. Commented Oct 17, 2012 at 7:08
  • 5
    command is uninitialised, unless that code has been omitted? Commented Oct 17, 2012 at 7:10
  • 2
    It runs without segfaulting for me. Commented Oct 17, 2012 at 7:19
  • Here too runs without segfault... In using ubuntu. Commented Oct 17, 2012 at 7:20
  • 2
    Please post a small compilable program that exhibits the problem. I can't see how the posted code can cause a segmentation fault with that input (even though there is no array bounds protection on tokens). Commented Oct 17, 2012 at 7:20

3 Answers 3

2

command is uninitialised. That means that the strlen(command) call might run beyond the 500 bytes, causing a segmentation fault.

Initialise your command array before using it. For example with memset.

Other than that, there is no bounds checking whatsoever and some arbitrary array lengths. This is bound to fail.

Sign up to request clarification or add additional context in comments.

1 Comment

Where does it segfault? You can use a debugger to find out.
1

You have a problem with tokens. You are incrementing j and k in each iteration without any check.

Anyway, dou you know there already exists functions that do what you wanna do?

Comments

0

To add More into other folks answer, you can use strsep. Look at the following sample code:

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


int main ()
{
char * command=NULL, *tok=NULL;

command =strdup("asdadas asdasdas asdadas");
while ((tok = strsep(&command, " ")) != NULL )
{
  printf ("..%s..\n", tok);
}

Hope it helps. ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.