在用户输入字符串上使用 strlen 时出现分段错误
Segmentation fault when using strlen on user input string
我正在尝试了解我的代码有什么问题。
我有一个由用户输入插入的单词组成的字符串。
我已经终止了字符串,所以应该没问题。
那我再用一个循环把单词的方向颠倒过来。但是当我在字符串的最后一个单词上调用 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]='[=10=]';
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;
在你的代码中。
while(c != '\n')
在第一次迭代中,c
未初始化。它调用 undefined behaviour 以使用未显式初始化的自动局部变量的值。
getc()
returns 有时 int
可能 不适合 到 char
。将 c
的类型更改为 int
.
就是说,正如您在问题中提到的,您从 strlen()
得到了段错误,您需要检查传递给 strlen()
的指针的非 NULL 值。标记化后立即将 NULL 检查添加到 pch
。
主要问题是:
while (pch != NULL) {
pch = strtok (NULL, s);
printf("%s\n",pch);
messl += 1 + strlen(pch);
当strtok
returnsNULL
时,你继续调用printf
和strlen
就可以了。您需要在调用 strtok
后立即测试 pch
。例如循环结构可以是:
while ( (pch = strtok(NULL, s)) != NULL ) {
正如其他 answerers/commentors 所指出的那样,还有其他各种问题。
我正在尝试了解我的代码有什么问题。 我有一个由用户输入插入的单词组成的字符串。 我已经终止了字符串,所以应该没问题。
那我再用一个循环把单词的方向颠倒过来。但是当我在字符串的最后一个单词上调用 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]='[=10=]';
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;
在你的代码中。
while(c != '\n')
在第一次迭代中,c
未初始化。它调用 undefined behaviour 以使用未显式初始化的自动局部变量的值。
getc()
returns 有时 int
可能 不适合 到 char
。将 c
的类型更改为 int
.
就是说,正如您在问题中提到的,您从 strlen()
得到了段错误,您需要检查传递给 strlen()
的指针的非 NULL 值。标记化后立即将 NULL 检查添加到 pch
。
主要问题是:
while (pch != NULL) {
pch = strtok (NULL, s);
printf("%s\n",pch);
messl += 1 + strlen(pch);
当strtok
returnsNULL
时,你继续调用printf
和strlen
就可以了。您需要在调用 strtok
后立即测试 pch
。例如循环结构可以是:
while ( (pch = strtok(NULL, s)) != NULL ) {
正如其他 answerers/commentors 所指出的那样,还有其他各种问题。