1

I am writing a custom edit control(C++/Win32) and have already gotten the basic functionality up an running.

  • I use a c-style buffer to store the contents of the visible text in the edit control. Now, I was wondering if I should use malloc/free combo to allocate memory from the heap, or should I go on using the new/delete pair?
  • I encountered a problem the other day. I created a dynamically
    allocated c -style string class member(char* szClassName). Then I
    initialized it in an initializer list as
    szClassName("name of class").

    When I used 'delete szClassName' in my destructor, it lead to some memory allocation error. Coould you guys tell me the problem
    here?

Finally, could you guys give me some tips on memory management that you found useful in your own programming ventures?

Thanks,

Devjeet!

devjeetroy
  • 1,855
  • 6
  • 26
  • 43

1 Answers1

2

I created a dynamically allocated c -style string class member(char* szClassName). Then I initialized it in an initializer list as szClassName("name of class").

No, you didn't. First, you created A POINTER to a char. Then you initialized the pointer with the address of the static literal string constant "name of class" (which the compiler would have allocated in the read-only data segment of the object file).

So, when your destructor called delete szClassName, you were trying to deallocate a block of memory in the read-only data segment rather than one that had been dynamically allocated with new (hence the error).

Stephen C. Steel
  • 4,380
  • 1
  • 20
  • 21