سؤال

I have this small piece of code:

int* index=(int*)(sizeof(int)*NB);
while(i < NB){
    printf("i=%d, pch=%s\n", i, pch);
    if (strcmp(pch, SPLIT_PATTERN))
      i++;
    else
      index[k++]=i-1;
    pch = strtok(NULL, "-");
  }

and with this input:

file_content EN7FSQcL63NRUQHSBBRDtVUkobmStQbKdL2cR7gpoC5-X2rS1Cu2RCYaw0TiGdYUUtYuCTB5WlE9Y3SJNuiimQC-ajksldnalmcjlakjflksjoi-
NB = 2
SPLIT_PATTERN = ajksldnalmcjlakjflksjoi (the last part in file_content)

C give me the segmentation fault error.

i=0, pch=EN7FSQcL63NRUQHSBBRDtVUkobmStQbKdL2cR7gpoC5
i=1, pch=X2rS1Cu2RCYaw0TiGdYUUtYuCTB5WlE9Y3SJNuiimQC
Segmentation fault (core dumped)

Please let me know where I do it wrong?

هل كانت مفيدة؟

المحلول

I suspect you meant to use:

int* index=(int*)malloc(sizeof(int)*NB);

instead of

int* index=(int*)(sizeof(int)*NB); // malloc is missing.

You should use

int* index=malloc(sizeof(int)*NB);

Having that additional int* before malloc is not a good idea. Checkout the answer in this SO post - Do I cast the result of malloc?

نصائح أخرى

Possible errors with this code are:

int* index=(int*)malloc(sizeof(int)*NB);
while(i < NB){
    printf("i=%d, pch=%s\n", i, pch);
    if (strcmp(pch, SPLIT_PATTERN))
      i++;
    else
      index[k++]=i-1;
    pch = strtok(NULL, "-");
}

1)Incorrect value for k, maybe it's uninitialized, or it goes out of bounds?

2) strtok is called only with NULL as parameter. Here is a simple example of how this should work:

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

which gives output

Splitting string "- This, a sample string." into tokens:
This
a
sample
string

For more, read strtok ref.

Note that we do not cast what malloc returns. Why?

[EDIT]

However, your output implies that you are calling strtok before the while loop.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top