1
votes

Bash is telling me my pointer being freed was not allocated. I have made a small program that recreates this issue.

#include <iostream>
#include <cstring>
using namespace std;

void display(char* t);

int main()
{
  char normArray[1000];
  int size;

  cout << "Enter tv show: ";
  cin.getline(normArray, 1000);
  size = strlen(normArray);

  char* dynArray = new char[size];
  dynArray = normArray;

  display(dynArray);

  delete[] dynArray;

  return 0;
}

void display(char* t)
{
  cout << t << endl;
}

As you can see, "char* dynArray = new char[size]" should be allocating dynArray. "delete[] dynArray" should then be freeing that memory. Yet bash tells me that dynArray is not being allocated.

I've tried just doing "delete dynArray", however, bash warns that I should use delete[] since dynArray is being allocated using "new[]", yet then goes on to say I never allocated it. Any help would be greatly appreciated.

1
dynArray = normArray; means that the pointer dynArray now points to the buffer normArray, so your delete statement tries to delete normArray - M.M
I've now changed that line to strcpy(dynArray, normArray) and it has solved the issue. Thank you so much, M.M. - chasehaley

1 Answers

1
votes

You're pointing dynArray to normArray just after the call to new.

char* dynArray = new char[size];
dynArray = normArray; // <--- Problem

display(dynArray);

The delete[ ] then attempts to free normArray, which is not dynamically allocated.

If you're intending to copy normArray into dynArray, you'll need a loop or call something like strcpy/memcpy to copy over the contents to dynArray.

Basic example:

for ( size_t i = 0; i < size; i++)
{
    dynArray[i] = normArray[i];
}