0

I am writing a program that uses character arrays / c strings. Whenever I run the program, valgrind throws a 'definitely lost' block warning:

==8011== [X] bytes in [Y] blocks are definitely lost in loss record 1 of [Z]
==8011==    at 0x4A065BA: operator new[](unsigned long) (vg_replace_malloc.c:264)
==8011==    by 0x403D45: File::File(stat*, char const*) (File.cpp:15)
...

This is the source code for the constructor and destructor (the header contains definitions for id, isDir, lastModified, and name (name is of type const char*)):

10  File::File(struct stat *statdat, const char* strName)
11  {
12    id = statdat->st_ino;
13    isDir = S_ISDIR(statdat->st_mode);
14    lastModified = (statdat->st_mtime);
15    char* tempName = new char[strlen(strName)+1];
16    strcpy(tempName, strName);
17    name = tempName;
18    tempName = NULL;
19  }
20  
21  File::~File()
22  {
23    //delete [] name;
24  }

I have a couple questions with this.

a) Attempting to leave in delete in the destructor when compiling and running results in an instant crash due to an invalid pointer. Why can't I call delete on the character array?

b) I think I'm allocating the right amount of memory for the array. What is causing the memory leak when allocating new space? The error happens after the program stops (after valgrind's HEAP SUMMERY).

Tanaki
  • 2,575
  • 6
  • 30
  • 41
  • The `delete[] name;` in the destructor should cover it. Also, have you considered using an std::string? Would be easier to manage. Also, I wouldn't bother with the tempName variable. I would just use the this->name char*. (Just a style note, not related to correctness) – Corbin Apr 23 '12 at 23:33
  • @Corbin, this does not work. Firstly, I cannot use strcpy on a const char*, so I am using tempName as a workaround. Second, uncommenting delete causes a bunch of valgrind complaints about uninitialized values and invalid free/delete/delete[] s. – Tanaki Apr 23 '12 at 23:39
  • The second arguement to strcpy is a `const char *`. Also, the code you posted, assuming `new` isn't erroring, the delete[] in the destructor is correct (unless you're already freeing it somewhere else). Can you post the entire class definition? – Corbin Apr 24 '12 at 02:43

1 Answers1

1

I have determined the issue.

My problem was with the /default/ constructor. Since it did not initialize 'name', the delete keyword was trying to delete a null pointer when the destructor was called on an object created by the default constructor. I modified my default constructor for File in order to initialize name to '\0', which appears to have solved the problem.

Tanaki
  • 2,575
  • 6
  • 30
  • 41