简体   繁体   中英

Segmentation fault - split string

Can you please help me with fixing below code. Not sure where the segmentation fault is.

 char str[] = "00ab00,00cd00";
 char **strptr;
 int i;

 strptr = malloc(sizeof(char*) * 2);

 strcnt = 0;
 int j=0;
 for(i=0;i<sizeof(str);i++) {

   char c = *(str+i);
   printf("%c", c);

   if(c==',') {
     strcnt++;
     j=0;
   }

   strptr[strcnt][j++] = c;

 }

Please ignore my poor coding :)

PS: I know its possible to split using strtok() easily.

Not sure where the segmentation fault is

As others have mentioned in the comments, you are not assigning memory to the pointers strptr[0] and strptr[1] but, you are trying to access them. This leads to segmentation fault.

Use a for loop to initially assign memory to strptr[0] and strptr[1]

strptr = malloc(sizeof(char*) * 2);
for(i = 0; i < 2; i++) //here, initialise each to 1 byte
{
    strptr[i] = malloc(1); 
}
strcnt = 0;

Here's a question on how to initialise a pointer to a pointer .


then, resize them at each step as you add additional character using the realloc() function.

for(i = 0, j = 0; i < sizeof(str); i++) 
{

   strptr[strcnt] = realloc(strptr[strcnt], j + 2); 
   //here, you resize each time to provide space for additional character using realloc() 
   char c = *(str + i);

   printf("%c", c);

   if(c == ',') 
   {
     ++strcnt;
     j=0;
     continue; //use a continue here
   }

   strptr[strcnt][j] = c;
   strptr[strcnt][++j] = '\0'; 
   //to provide null terminating character at the end of string (updated to next position at every iteration)
}

don't forget to free() the allocated memory

for( i=0; i<2; i++)
{
    printf("%s\n", strptr[i]); //just to display the string before `free`ing
    free(strptr[i]);
}

free(strptr);

Altogether your code would be something like this:

char str[] = "00ab00,00cd00";
char **strptr;

int i, j;
int strcnt; 

strptr = malloc(sizeof(char*) * 2);
for(i = 0; i < 2; i++)
{
    strptr[i] = malloc(1); 
}
strcnt = 0;


for(i = 0, j = 0; i < sizeof(str); i++) 
{

   strptr[strcnt] = realloc(strptr[strcnt], j + 2); 
   char c = *(str + i);

   printf("%c", c);

   if(c == ',') 
   {
     ++strcnt;
     j=0;
     continue;
   }

   strptr[strcnt][j] = c;
   strptr[strcnt][++j] = '\0';
}

for( i=0; i<2; i++)
{
    printf("%s\n", strptr[i]);
    free(strptr[i]);
}

free(strptr);

return 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM