0

When I allocate memory and do not call delete, is this undefined behaviour?

Example:

int main(int argc, char** argv) {
    int* a = new int[1];
    // next code only to prevent optimization (hopefully)
    *a = argc; std::cout << *a << std::endl;
    // no delete
    return 0;
}

(Let us assume the new is not optimized out).

CharlesB
  • 80,832
  • 27
  • 184
  • 208
Danvil
  • 21,262
  • 19
  • 63
  • 87

1 Answers1

0

It's not undefined behaviour; it's a memory leak.

Of course leaks "exist" only as long as the process is still running; in this case the process exits (and the concept of leak becomes moot) immediately afterwards.

Jon
  • 413,451
  • 75
  • 717
  • 787
  • I would say it is undefined behaviour, since the program relies on side-effects of the call to the destructor (i.e. the program could run out of memory if it isn't called.) But it isn't crystal clear. – juanchopanza Jun 10 '14 at 08:57
  • Who downvoted this and why? I would like to understand if a statement is wrong or something? (upvoted) –  Jun 10 '14 at 08:57
  • @juanchopanza: Sorry, what? The program clearly does not rely on any side effects, there is no destructor to begin with because `int[]` is not a class type, and running out of memory is not undefined behavior anyway. – Jon Jun 10 '14 at 09:01
  • Sorry, I still had [a similar, recent question](http://stackoverflow.com/questions/24136120/what-is-wrong-with-using-arrays-dynamically-allocated-in-c) in my head, where the array was one of `std::string`. – juanchopanza Jun 10 '14 at 09:03