0

My code:

wchar_t buffer[64];

wsprintf(buffer, L"%d, %d, %d", x, y, z);
SendMessage(hwndEdit, WM_SETTEXT, NULL, (LPARAM)buffer);

free(buffer); // <-- crashes

The code works fine when NOT freeing the buffer, however crashes when free(buffer) is used.

Is this line necessary, if not, why not? Isn't there a need to free memory after it's used?

ChaseTheSun
  • 3,810
  • 3
  • 18
  • 16

1 Answers1

3

The buffer is allocated on stack, not on the heap, you don't need to free it by yourself.

If buffer is created dynamically using malloc (in C) or new (in C++), you need free (in C) or delete (in C++). Dynamic arrays are created on the heap. static arrays (size known at compile time) are allocated on stack.

taocp
  • 23,276
  • 10
  • 49
  • 62
  • I see, so when should i free a buffer? How do I know if the buffer is allocated on stack or not? – ChaseTheSun Apr 24 '13 at 01:56
  • @ChaseTheSun If you _explicitly_ allocates the buffer, with e.g. `malloc` or similar function, then you need to free it. Variables on the stack are handled completely by the compiler. – Some programmer dude Apr 24 '13 at 01:58
  • Which is, of course, why you should always prefer this approach whenever possible: it prevents memory leaks and offloads tedious work to the compiler. – Cody Gray - on strike Apr 24 '13 at 05:15
  • this is all well and good, except he doesn't know what you mean by on the stack, most likely. Especially since the C standard doesn't even require the implementation to use one. – Randy Howard Apr 24 '13 at 05:31