【发布时间】:2013-03-02 19:34:10
【问题描述】:
我正在尝试使用 getline() 从键盘获取输入,将其存储在字符串中,对其进行标记,然后打印标记。当我运行它时,我在最后一次迭代(处理来自输入的最后一个标记的迭代)上得到一个 Segmentation Fault 错误。
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
////////////////////////
// Main Method //
////////////////////////
void main() {
system("clear");
int ShInUse = 1; // Represents if shell is in use
char curpath[1024]; // holds current path to print with prompt
char *UserCommand = NULL;
size_t combytes = 100;
UserCommand = (char *) malloc(combytes);
char *tok;
// Main loop that shell uses //
while (ShInUse == 1) {
getcwd(curpath, sizeof(curpath)); // Store initial working dir
printf("gash:%s>", curpath); // print prompt
getline(&UserCommand, &combytes, stdin);
tok = strtok(UserCommand, " \n"); // Tokenize input
if (tok == NULL ) {
printf("Enter a command.\n");
} else {
// Exit command //
if (strcmp(tok, "exit") == 0) {
ShInUse = 0;
} else {
while (tok != NULL ) {
printf("You entered a command.\n");
printf("tok: %s\n", tok);
tok = strtok(NULL, " \n");
}
}
}
}
free(UserCommand);
}
关于可能导致此问题的任何想法?目前,调试不是我的选择。
【问题讨论】:
-
也许你忘记将 UserCommand 初始化为 NULL ?
-
逐行注释代码以查看段错误发生的确切位置。
-
@wildplasser 感谢您的回复。我试过了,但它仍然没有用。我忘了包含我的字符串修饰符,我会将它们添加到我的帖子中。
-
@wildplasser 是的,我很清楚。我以前从未听说过,现在我真的很好奇。
标签: c string token tokenize strtok