简体   繁体   中英

Segmentation Fault with strlen

I am getting a segmentation fault error. When I comment out "wordlength = strlen(token);" it runs fine. I don't know why it the seg fault happens when I assign a strlen(token) just fine to an int a few lines before this one. I would appreciate any help possible.

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

#define char_max 60
int main(int argc, char *argv[])
{
    FILE *fp = fopen(argv[2],"r");

    char **wordlist;
    int row = 1;
    int i;
    char temp[100];
    char *token;
    int wordlength;
    int lengthcounter;
    wordlist = (char**)malloc(row*sizeof(char*));
    for(i = 0; i < row; i++)
    {
         wordlist[i] = (char*)malloc(char_max*sizeof(char*));
    }

    while(fgets(temp, sizeof(temp), fp) != NULL)
    {
        lengthcounter = 0;
        wordlength = 0;

        token = strtok(temp, " ");
        strcat(wordlist[row-1], token);
        printf("%s\n", wordlist[row-1]);
        lengthcounter = strlen(token);

        while(token != NULL)
        {
            token = strtok(NULL, " ");
            wordlength = strlen(token);
            /*lengthcounter += wordlength;*/ 
        }

        printf("The lengthcounter is %d\n", lengthcounter);

    }

    free(wordlist);
    fclose(fp);

    return 0;
    }
    while(token != NULL)
    {
        token = strtok(NULL, " ");
        wordlength = strlen(token);
        /*lengthcounter += wordlength;*/ 
    }

What happens in the last iteration of the loop when token is NULL ? You pass it to strlen anyway.

Also, this is almost certainly wrong:

     wordlist[i] = (char*)malloc(char_max*sizeof(char*));

You're allocating space for pointers, not characters. So why sizeof(char*) ? Also, don't cast the return value of malloc . This is C, not C++.

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