在用户输入字符串上使用strlen时出现分段错误

时间:2015-07-31 07:48:43

标签: c segmentation-fault strlen

我试图了解我的代码有什么问题。 我有一个由用户输入插入的单词组成的字符串。 我已经终止了字符串,所以它应该没问题。

然后我用另一个循环来反转单词的方向。但是当我在字符串的最后一个字上调用STRLEN时,它会给我分段错误。 (逆转部分尚未完成,因为我遇到了这个问题)。

为什么呢?

以下是代码:

char *frase, c;
int i=0;
int d=1; 
frase = (char*)malloc(sizeof(char)); 

printf("Insert phrase: ");
while(c != '\n') { 
    c = getc(stdin);     
    frase = (char*)realloc(frase,d*sizeof(char)); //dynamic allocation
    frase[i] = c;
    d++;
    i++;
}

//at the end i terminate the string
frase[i]='\0';
printf("\nInserted phrase: %s\n",frase);

// here I start the reversal, first of all I separate all the words
char *pch;
char s[2] = " ";
int messl=0;

pch = strtok (frase,s);
printf ("%s\n",pch);
messl += 1 + strlen(pch);
printf ("Lung stringa = %d\n",messl);
char *message = (char*) malloc(messl);

while (pch != NULL) {
    pch = strtok (NULL, s);
    printf("%s\n",pch);
    messl += 1 + strlen(pch); //in the last cycle of the loop I get the error

}
//printf ("%s\n",message);
return 0;

2 个答案:

答案 0 :(得分:4)

在您的代码中。

 while(c != '\n')

在第一次迭代时,c未初始化。它调用undefined behaviour来使用尚未显式初始化的自动局部变量的值。

getc()会返回int,有时可能不适合进入char。将c的类型更改为int

也就是说,正如您在问题中提到的那样,您从strlen()获得了段错误,您需要检查传递指针{NULL}的非NULL值。在标记化后立即将NULL检查添加到strlen()

答案 1 :(得分:2)

主要问题是:

while (pch != NULL) {
    pch = strtok (NULL, s);
    printf("%s\n",pch);
    messl += 1 + strlen(pch); 

strtok返回NULL时,您会继续致电printfstrlen。您需要在致电pch时立即测试strtok。例如,循环结构可以是:

while ( (pch = strtok(NULL, s)) != NULL ) {

还有其他各种问题,正如其他答复者/评论员所指出的那样。