0

It's probably very basic but I am stuck and simply don't know what the problem is.

The main code is predefined as a task. The goal is to use const as much as possible. The following constructor is just supposed to copy the literal string to the const m_data and that works fine but I am not able to free the memory - it always leaves 1 block. What am I missing?

main.cpp

#include <iostream>
#include "immstring.hpp"
using namespace std;
using namespace Util;

int main() 
{
  const ImmutableString s1("Hello");
}

immu.hpp

#include <cstring>
namespace Util {
class ImmutableString {
public:
    ImmutableString(const char* src);
    ~ImmutableString();

private:
    char* const m_data;
};
}

immu.cpp

#include "immstring.hpp"
#include <iostream>
#include <cstring>
namespace Util 
{
ImmutableString::ImmutableString(const char* src)
    :m_data{strcpy(new char[strlen(src)+1],src)}{}

ImmutableString::~ImmutableString() 
{
    delete m_data;
}
}
dustinboettcher
  • 415
  • 1
  • 5
  • 19

1 Answers1

1

To leave all array memories blocks you have to use delete like this :

delete[] m_data;

Thanks, Robin.

Robin M.
  • 66
  • 3