C++ 模板特化 char* 和 Valgrind

标签 c++ templates memory-leaks char 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;
}

测试.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

测试.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 []

关于C++ 模板特化 char* 和 Valgrind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30277660/

相关文章:

c++ - 模板继承的 VC++ 错误

c++ - 在模板中实例化模板对象

c++ - 引用 const 的模板特化

c++ - 使用默认参数转发引用?

android - GetByteArrayRegion 导致 ArrayIndexOutOfBoundsException

c++ - 如何抑制::system ("del *.log"的输出)出现在控制台中

c++ - 对同一图形应用多个同时旋转

c++ - Visual Studio C++ 项目中的奇怪内存泄漏

c++ - 查找数组之间的内存泄漏

c++ STL vector 导致内存溢出?