gpt4 book ai didi

c - fscanf 在什么情况下会溢出内存?

转载 作者:太空宇宙 更新时间:2023-11-04 07:21:24 24 4
gpt4 key购买 nike

我有一个我实现的链表,它适用于各种文件输入(它逐行读取并插入它们。)

void insert_words(FILE* file, node_type* list)
{
char buffer[12];
int length = 0;

while (!feof(file)){
fscanf(file, "%s", buffer);//buffer contains the string/name
length = strlen(buffer);
if (length != 0) {
insert_sorted(list, buffer);
}
} //while

}

鉴于此代码,我发现在读取“fff”后使用给定样本输入执行 fscanf 时,事情似乎变糟了。

one
two

three ee
fff
ee

在解析 ee 时:

list = 0x009dfac0 {name=0x009dfac0 "one" next=0x00c98c08 {name=0x00c98c08 "three" next=0x00c98ba0 {name=0x00c98ba0 "two" ...} } }

在下一个标记之后:

list = 0x009dfac0 {name=0x009dfac0 "ee" next=0x009df068 {name=0x009df068 "È”ü\xf\x1" next=0x0ff7caa0 {msvcr110d.dll!_except_handler4(_EXCEPTION_RECORD *, _EXCEPTION_REGISTRATION_RECORD *, _CONTEXT *, void *)} {...} } 

检查我的列表时,“下一个”指针在 fscanf 被触发后立即损坏。潜在的原因是什么?

根据要求插入排序:

void insert_sorted(node_type* list, char* value)
{
// Copy our pointer so we can move around
node_type *n = (node_type*) malloc(sizeof *n);
node_type *loc = NULL;
node_type *tmp;
node_type dat;
node_type* prev = list;
node_type* head = list;

n->next = NULL;
strcpy(n->name, value);

// First element, assign immediately
if( strcmp(list->name, "") == 0 )
{
*list = *n;
return;
}


while(head != NULL)
{
// We should do a comparison to see if one is greater than another
int cmp_result = strcmp(value, head->name);

// If the value is bigger, this means the value needs to be inserted after
if(cmp_result > 0)
{
loc = head;
}

else if (cmp_result < 0) // this needs to be ahead
{

if(prev == head)
{
dat = *head;
*head = *n;
head->next = &dat;
return;
}

prev->next = n;
n->next = head;
return;
}

else if(cmp_result == 0)
{
free(n);
return; // duplicate, die
}


// Advance to the next pointer
prev = head;
head = head->next;
}


// You've reached the end, that must mean you've succesfully reached the point to insert

tmp = loc->next; // get the value we're going to end up detaching
n->next = tmp; // link the two together
loc->next = n;

}

最佳答案

将循环修改为

while (fscanf(file, "%s", buffer) == 1) {
length = strlen(buffer);
// ...
}

因为 feof(file) 在上次成功的 fscanf() 之后仍然返回 0。它在第一个失败 fscanf() 后返回非 0。

关于insert_sorted(),看下面几行:

            head->next = &dat;
return;

因为 dat 是本地对象,一旦函数返回,保存它的地址会导致地址无效。

关于c - fscanf 在什么情况下会溢出内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21446845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com