Xyzk
Xyzk

Reputation: 1332

Segmentation fault (11)

I've got segmentation fault in my C program, and I don't know why. It fails after "debug 6", which is printed out and then "segmentation fault(11). I have a hunch it's because of my str_split_2 function. This program is supposed to read file, first line has n, then n lines with two values "a,b" . I want to save those values to 2 dimensional array map.

char** str_split_2(char* str, const char delim)
{
    char** result;
    result=(char**)malloc(2*sizeof(char*));
    result[0] = strtok(str, &delim);
    result[1] = strtok(NULL, &delim);
    return result;
}


int loadFile(int*** map, char* filename,int *n)
{
    int i=0;
    char *line = NULL;
    size_t len;
    FILE *fptr = fopen(filename, "r");
    if(fptr == NULL)
    {
        fprintf(stderr, "Error opening a file: %s\n", filename);
        return 1;
    }

    getline(&line, &len, fptr);
    *n = atoi(line);
    printf("n: %d\n",*n);
    *map = (int**) malloc((*n)*sizeof(int*));
    if(*map==NULL)
        return 1;
    char** sPosition=NULL;
    printf("debug 0\n");
    for(i=0; i<*n; i++)
    {
        *map[i]=(int*) malloc(2*sizeof(int));
        printf("debut 1\n");
        if(*map[i]==NULL)
            return 1;
        printf("debug 2\n");
        getline(&line, &len, fptr);
        sPosition=str_split_2(line,',');
        printf("debug 3\n");
        printf("%s\n%s\n",sPosition[0],sPosition[1]);
        printf("debug 4\n");
        *map[i][0]=atoi(sPosition[0]);
         printf("debug 5 %d\n",*map[i][0]);
        *map[i][1]=atoi(sPosition[1]);
         printf("debug 6 %d\n",*map[i][1]);
         printf("hello");
        printf("%d:",i);
    }

fclose(fptr);
free(line);
return 0;
}

Upvotes: 1

Views: 272

Answers (2)

barak manos
barak manos

Reputation: 30136

Second argument passed to strtok must be a pointer to a null-terminated string (i.e., the string must end with a 0 character).

You are passing a pointer to a character variable (char delim), and strtok "scans" memory from this address and until a 0 value is encountered, thus most likely performing an illegal memory access at some point.

BTW, this is the case with all str routines, such as strcpy, strlen, strcmp.

Upvotes: 0

Guntram Blohm
Guntram Blohm

Reputation: 9819

I think that

*map[i]=(int*) malloc(2*sizeof(int));

should be one of

(*map)[i]=(int*) malloc(2*sizeof(int));
map[0][i]=(int*) malloc(2*sizeof(int));

else it will mean

*(map[i])=(int*) malloc(2*sizeof(int));

which seems to be wrong. Of course, the same problem is in

    *map[i][0]=atoi(sPosition[0]);
     printf("debug 5 %d\n",*map[i][0]);
    *map[i][1]=atoi(sPosition[1]);
     printf("debug 6 %d\n",*map[i][1]);

Upvotes: 2

Related Questions