c++模板专门化char*和Valgrind

C++ Templates specialisation char* and Valgrind

本文关键字:Valgrind char 专门化 c++      更新时间:2023-10-16

我的程序有一个很大的内存泄漏问题。我使用Valgrind来检查内存泄漏,并进行了一些更改,我得到了大约20或40个错误,但仍然无法消除所有错误,也不知道如何消除。我不能改变main函数中的代码,我必须适应它。我不能将专门化更改为字符串!问题是什么是一个适当的方式来管理char*和内存。

规则:

  1. 主代码不可更改

  2. 不要在任何智能指针或其他类型中打包char*。

问题

使用char*与容器管理内存

还有可能吗?或代替容器安全通常分配数组?

char*的析构函数有什么问题?

My main function:

#include <iostream>
#include "test.h"
#include <vector>
using namespace std;
int main()
{
char * cpt[]={"tab","tab2","tab3"};
test<char*> test1;
test1.addItem(cpt[1]);
char * item=test1.getItem(0);
item[0]='Z';
cout<<item<<endl;
return 0;
}

test.h

#ifndef TEST_H
#define TEST_H
#include <vector>
using namespace std;
template<class T>
class test
{
 public:
   ~test();
  void addItem(T element){
  elements.push_back(element);
  }
  T getItem(int i){
  return elements[i];
  }
  vector<T> elements;
};
#endif // TEST_H

test.cpp

#include "test.h"
#include <iostream>
#include <cstring>
using namespace std;
template<>
char * test<char*>::getItem(int i)
{
  /*char *nowy=new char(strlen(elements[i])+1);
  //strcpy(nowy,elements[i]);
  return nowy;
  //with above code 39 errorr in Valgrind
  */
  return elements[i]; // with this instead of above 19 errors in Valgrind
  }
  template<>
void test<char*>::addItem(char* element){
  char * c= new char( strlen (element)+1);
  strcpy(c,element);
  elements.push_back(c);
  }
  template<>
 test<char*>:: ~test(){
 for( auto v: elements)
 delete []v; //with this 20 errors
 //delete v; instead of above line 19 errors;
 }

你应该替换

new char(strlen (element) + 1); // this allocate one char with given initial value

new char[strlen (element) + 1]; // array of (uninitialized) char

分配char数组

那么你必须调用delete []