带有strlen的分段错误

时间:2015-04-18 02:14:29

标签: c

我收到了分段错误错误。当我注释掉“wordlength = strlen(token);”时它运行正常。我不知道为什么当我在这之前将一个strlen(token)分配给一个int几行时,就会发生seg错误。我将不胜感激任何帮助。

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

1 个答案:

答案 0 :(得分:3)

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

token NULL时,循环的最后一次迭代会发生什么?无论如何,你将它传递给strlen

此外,这几乎肯定是错误的:

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

您为指针分配空间,而不是字符。那么为什么sizeof(char*)?另外,不要强制转换malloc的返回值。这是C,而不是C ++。