OMG_Kitty
OMG_Kitty

Reputation: 3

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;
    }

Upvotes: 0

Views: 1257

Answers (1)

David Schwartz
David Schwartz

Reputation: 182885

    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++.

Upvotes: 3

Related Questions