gpt4 book ai didi

c++ - C-LinkedList Append Function, with Bad Memory Address 错误

转载 作者:行者123 更新时间:2023-11-28 06:18:48 25 4
gpt4 key购买 nike

我想了解为什么编译器会检测到“坏内存错误”据我了解 (Pointer->next != null) 应该让我到达尾部,但为什么当它到达最后一个节点时,它会检测到错误。

void Append(Data* head, char* name, char* lastname) { 
Data* _newNode = (Data*)malloc(sizeof(Data));
std::strcpy(_newNode->name, name);
std::strcpy(_newNode->lastname, lastname);
// Iretator
Data* prt = head;
if ((*name != '\0') && (*lastname != '\0')) {
// find the last node in the list:
//Special Case
if (*head->name == '\0') {
std::strcpy(head->name, name);
std::strcpy(head->lastname, lastname);
} else {
while ((int*)prt->next != NULL) {
prt = prt->next;
}
prt = _newNode;
}
}
}

最佳答案

这里忽略 C 和 C++ 的混合。一个主要问题是您忘记了行

_newNode->next = NULL;

在使用 malloc 创建新节点并初始化姓名和姓氏之后。否则,您的 while 循环无法保证按预期工作。

另一个主要问题是 while 之后的函数末尾:while 循环循环直到 ptr->next == NULL。所以它指向最后一个条目。并且您想将新节点附加到最后一个条目。

ptr = _newNode; // <<-- WRONG!
ptr->next = _newNode; // this is what you need.

除此之外,您的代码没有以稳健可靠的方式编写。这是一个略微改进的版本,其中包含重要检查。

#define MAX_NAME_LEN 10-1
#define MAX_LAST_NAME_LEN 10-1

void Append(Data *head, char *name, char *lastname)
{
// Check preconditions:
if (NULL == head)
return;
if (NULL == name)
return;
if (NULL == lastname)
return;
if( 0 == strlen(name) )
return;
if( 0 == strlen(lastname) )
return;
if (MAX_NAME_LEN < strlen(name) || MAX_LAST_NAME_LEN < strlen(lastname))
return; // too long name or lastname

// implementation

// Try to re-use an empty head node.
if (*head->name == '\0') // alien code, covering up for
{
std::strcpy(head->name, name); // some flaw in the design or other
std::strcpy(head->lastname, lastname); // functions
return;
}

// we need a new one.
Data *_newNode = (Data*)malloc(sizeof(Data)); // can return NULL, not checked
if (NULL != _newNode)
{
std::strcpy(_newNode->name, name); // can overwrite memory
std::strcpy(_newNode->lastname, lastname); // can overwrite memory
_newNode->next = NULL; // + _newNode->next not initialized to NULL <-- MAIN ERROR!
// Iretator
Data *prt = head;
while (prt->next != NULL) // (int*) not needed, not good
{
prt = prt->next;
}
prt->next = _newNode; // + the prt points to the last entry
// and the new node is appended.
// the original code was assigning newNode to ptr.

}
}

关于c++ - C-LinkedList Append Function, with Bad Memory Address 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29708255/

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