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).