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.
data[i]=(char *)malloc(sizeof(char)*l)+1);
this typo I do not see any issue here and ofcource you need to freefree(data)
before assigning it toNULL
. – kiran Biradardata[i]
isn't a value returned bymalloc()
, so the freeing probably goes haywire, and there's overwriting beyond the end of the buffer too. – Jonathan Leffler