1
votes

Take a string from the user as a single command line argument. Tokenize and store it in appropriate data structures and then display it.

I tried this code but it gives me a segmentation fault. I am unable to find out where it is.

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


#define delim " "

int main(int argc, char *argv[])
{

    if(argc!=2)
    {
        printf("\nPlease enter only one argument as a single line string.\n");
        exit (-1);
    }

    char *tmp1=NULL;
    int len=0;
    int count=0;
    int i=0;
    len=strlen(argv[1]);
    tmp1=(char *)malloc(sizeof(char)* (len)+1);

    if(NULL==tmp1)
    {
        printf("Memory allocation failure single ptr.");
        exit (-1);
    }

    strcpy(tmp1,argv[1]);
    char *tok=NULL;
    char **data=NULL;
    tok=strtok(tmp1,delim);

    while(NULL!=tok)
    {
        count++;
        tok=strtok(NULL,delim);
    }

     strcpy(tmp1,argv[1]);

     data=(char**)malloc(sizeof(char*)*count);
     if(NULL==data)
     {
         printf("Memory allocation failure double ptr.");
         exit (-1);
     }


     tok=strtok(tmp1,delim);
     while (NULL!=tok)
     {
         int l=strlen(tok);
         data[i]=(char *)malloc(sizeof(char)*l)+1);
         if(NULL==data[i])
         {
             printf("Memory allocation failure ");
             exit (-1);
         }


         strcpy(data[i],tok);
         tok=strtok(NULL,delim);
         i++;
     }

     for (i=0; i<count; i++)
     {
         printf("%s\t",data[i]);
     }
     for (i=0; i<count; i++)
     {
         free(data[i]);
         data[i]=NULL;
     }
     data=NULL;

     free(tmp1);
     tmp1=NULL;
     return 0;
}

I passed "Hello this is the string" and it results in a segmentation fault.

1
Apart from data[i]=(char *)malloc(sizeof(char)*l)+1); this typo I do not see any issue here and ofcource you need to free free(data) before assigning it to NULL .kiran Biradar
That could be an interesting typo if it compiled; it would lead to undefined behaviour as data[i] isn't a value returned by malloc(), so the freeing probably goes haywire, and there's overwriting beyond the end of the buffer too.Jonathan Leffler
Please run your code in a debugger and pinpoint the instruction where the segmentation fault occurs.the busybee

1 Answers

0
votes

As I understand from running your code, you want to enter a string as argument and just parse it and print it, as simple as that right?

the code isn't compiling due to a typo in line:

data[i]=(char *)malloc(sizeof(char)*l)+1);

After fixing it to:

data[i]=(char *)malloc(sizeof(char)*l+1);

The output of the code is, for "hello this is string":

hello   this    is      string                                                                                                                           

...Program finished with exit code 0 

If you still have segmentation error please post more information