尝试从文件中获取令牌时出现分段错误。 [英] Segmentation Fault while trying to grab tokens from file.
问题描述
您好,
我正在尝试从C下的文件中获取令牌,进入预先分配的缓冲区。到目前为止看起来像这样:
Hello,
I'm trying get "tokens" from a file under C, into a preallocated buffer. So far it looks like this:
char* token;
....
int main(int argc, const char* argv[])
{
....
token = (char*)malloc(256);
grab_token();
....
}
void grab_token()
{
char a;
int i = 0;
while(a == ' ' || a == '\t' || a == '\r' || a == '\n' || a != EOF) { a = fgetc(source_FILE); }
while(a != ' ' || a != '\t' || a != '\r' || a != '\n' || a != EOF)
{
a = fgetc(source_FILE);
token[i] = a;
i++;
}
// NULL terminate token
token[i+1] = '\0';
}
现在这很简单,只需检查收到的字符是否为空格,制表符,换行符....或者如果是EOF则退出它从文件中获取words或tokens并将其放入已分配的缓冲区中。然而,grab_token()特别失败了臭名昭着的分段错误(核心转储),SIGEGV意味着无效的内存访问,但由于某种原因我不明白为什么我应该访问我没有分配的内存。是的,fgetc()完美运行。
It's quite simple for now, just checks if the character received is a whitespace, tab, newline.... or exits if it's an EOF or it takes "words" or "tokens" from the file and puts it in an allocated buffer. However the "grab_token()" specifically fails with the infamous "Segmentation Fault (Core Dumped)", with SIGEGV which means invalid memory access, however for some reason I don't see why I should be accessing memory I haven't allocated. And yes, fgetc() works perfectly.
推荐答案
你正在使用OR(||
)你应该在哪里改为使用AND(&&
)。
您没有检查令牌$ c上的缓冲区溢出$ c>(实际上你甚至不检查
malloc
是否成功)。
You are using OR (||
) where you should use instead AND (&&
).
You are not checking for buffer overrun ontoken
(actually you are not checking even ifmalloc
succeeded).
CPallini是对的。但要更清楚,请参阅以下代码。它包括一些评论和建议。你可以根据自己的需要改变它。我没有测试过代码,但我认为不会有任何核心转储(如果它成功编译:))。
CPallini is right. But to be more clear, see the following piece of code. It includes some comments and advices. you can change it according to your needs. I haven't tested the code, but I think there won't be any core dump (if it compiles successfully :) ).
// define size as constant
const int BUFF_SIZE = 256;
// 1- I would return some value to check if successful or not
// 2- pass 'token' pointer as parameter
// 3- dont use global variables if you dont have to do so.
void grab_token()
{
char a;
int i = 0;
while((a = fgetc(source_FILE))!=EOF) {
if(a == ' ' || a == '\t' || a == '\r' || a == '\n') // this part can be converted to macro
continue;
break;
}
if(a==EOF) {
token[0]=0;
// maybe some error handling
return;
}
while((a = fgetc(source_FILE))!=EOF) {
if(a == ' ' || a == '\t' || a == '\r' || a == '\n')
break;
if(i<BUFF_SIZE-2) // BUFF_SIZE-1 is reserved for termination
token[i++]=a;
else {
// some error handling
// break;
// or
// return;
}
}
token[i]=0;
}
这篇关于尝试从文件中获取令牌时出现分段错误。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!