C++ 模板专业化 char* 和 Valgrind

C++ Templates specialisation char* and Valgrind

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

规则:

  1. 主要代码不变

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

问题

使用 char* 和容器管理内存。

还有可能吗? 或者通常分配数组而不是容器更安全?

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

我的主要功能:

#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 []