【发布时间】:2020-05-20 15:44:51
【问题描述】:
我正在尝试实现链表。
linkedListType 类中的一种方法insertLast() 导致错误
这是linkedList.hpp文件中的函数
template<class dataType>
void linkedListType<dataType>::insertLast(dataType data)
{
nodeType<dataType> *newNode = new nodeType<dataType>();
newNode->info =data;
if (first==NULL) insertFirst(data);
else{
newNode->link=NULL;
last->link=newNode;
last=newNode;
}
}
template<class dataType>
void linkedListType<dataType>::destroyList()
{
nodeType<dataType> *temp;
while(first!=NULL){
temp = first;
first=first->link;
delete temp;
}
last=NULL;
count=0;
}
template<class dataType>
void linkedListType<dataType>::insertFirst(dataType data)
{
nodeType<dataType> *newNode = new nodeType<dataType>();
newNode->info=data;
if (first==NULL){
first=newNode;
last=newNode;
}
else{
newNode->link=first;
first=newNode;
}
}
这里是main 函数
#include <iostream>
#include "linkedList.hpp"
using namespace std;
int main()
{
linkedListType<string> names;
int numOfNames;
cout<<"\nEnter the number of names: ";cin>>numOfNames;
string name;
for(int i=0; i<numOfNames;i++) {
cin>>name;
names.insertLast(name);
}
names.destroyList();
}
当我使用命令时:
valgrind --leak-check=full ./a.out
==5528== Command: ./a.out
==5528==
Enter the number of names: 2
xyv
fds
==5528==
==5528== HEAP SUMMARY:
==5528== in use at exit: 40 bytes in 1 blocks
==5528== total heap usage: 6 allocs, 5 frees, 74,872 bytes allocated
==5528==
==5528== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==5528== at 0x4C3017F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5528== by 0x108F45: linkedListType<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::insertLast(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/abdo/cpp/linkedList/a.out)
==5528==
==5528== LEAK SUMMARY:
==5528== definitely lost: 40 bytes in 1 blocks
==5528== indirectly lost: 0 bytes in 0 blocks
==5528== possibly lost: 0 bytes in 0 blocks
==5528== still reachable: 0 bytes in 0 blocks
==5528== suppressed: 0 bytes in 0 blocks
==5528==
==5528== For counts of detected and suppressed errors, rerun with: -v
==5528== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
它给了我一个错误,那么我的代码有什么问题?
【问题讨论】:
-
也许解除分配
nodeType<dataType> *newNode或将其定义为空指针可以解决问题,如下:delete newNode或newNode = nullptr;。nullptr是在cstddef中定义的。 -
在
insertLast中你新建了一个新节点,如果first是nullptr你什么都不做......换句话说,你正在泄漏 -
@WBuck 根据日志,问题出在
insertLast,而不是insertFirst。 -
@WBuck 不,它需要
data,然后为data创建节点。 -
@NAND 不,它首先创建一个
node,然后检查first是否是NULL,如果是,它只传递给data到insertFirst。您已经创建的node得到leaked
标签: c++ memory-leaks dynamic-programming valgrind