-3

I know that we normally don't call operator new & operator delete function directly. Because If I do so constructor & destructor won't be called & it likely ends up with memory leak. But for primitive types this seems not problematic. Correct me If I am wrong.

Consider following program:

#include <iostream>
int main()
{
    int* p=(int*)operator new (3);
    std::cout<<*p;
    operator delete(p);
}

Why it prints garbage value as output? What I have done wrong here? I am curious to know about how to correctly give value by calling operator new function directly. I want the output of program 3 as a output, but by not using new operator like int* p=new int(3);. What should I do?

syntagma
  • 20,485
  • 13
  • 66
  • 121
Destructor
  • 13,235
  • 8
  • 48
  • 108

2 Answers2

3

You have two problems:

  1. You only allocate three bytes
  2. You don't initialize the memory you allocate.

Both of these will lead to undefined behavior.

The argument to the operator new function is the number of bytes to allocate, not what to initialize the allocated memory to.

The new operator, and the function operator new are two different things that behaves differently.

See this old question and answers for more details.

Community
  • 1
  • 1
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
1

I think the main misunderstanding in your code is that you think that here:

int* p=(int*)operator new (3);

You are doing this:

int* p = new int(3);

It prints garbage value because your int to which p points has not been initialized.

What you actually do is you allocate 3 bytes of memory for storing and int. So int pointer p will now point to memory are with 3 bytes allocated (on most platforms you need 4 bytes to store an int).

See the new C++ reference for more information (first overload is what you should check).

syntagma
  • 20,485
  • 13
  • 66
  • 121