user2837961
user2837961

Reputation: 1555

c++ Releasing memory of array pointer

I have a function as below

void ReadMyPacket(int Socket)
{
  char *inStartup = new char[2];
  int recvReturn = recv(Socket, inStartup, 2, 0);
  ...
  ...
  delete[] inStartup; 
}

How should I release the memory of inStartup? I cannot use std::string because I have to pass the array in the recv function.

Upvotes: 0

Views: 84

Answers (4)

Matthieu M.
Matthieu M.

Reputation: 299730

You have the syntax down right, however your reasoning is, slightly, flawed:

I cannot use std::string because I have to pass the array in the recv function.

While string might not be the right interface, vector definitely is. The primary reason for vector being a contiguous array is interoperability with C.

You can thus write:

void ReadMyPacket(int Socket)
{
  std::vector<char> inStartup(2);
  int recvReturn = recv(Socket, &inStartup.at(0), inStartup.size(), 0);
  //...
  //...

}

And this way you will avoid risks of forgetting to call delete[] yourself (for example, in case of exception).

Note: in C++11 and higher you can use inStartup.data() instead of &inStartup.at(0).

Upvotes: 2

Paul R
Paul R

Reputation: 212929

Dynamic allocation for a 2 character buffer is overkill - just use a local buffer on the stack:

void ReadMyPacket(int Socket)
{
  char inStartup[2];
  int recvReturn = recv(Socket, inStartup, 2, 0);
  ...
  ...
  // nothing to dispose of here
}

Upvotes: 2

ravi
ravi

Reputation: 10733

This is properly deleting the memory.

delete[] inStartup;

conjured up by

new []

Upvotes: 0

Arkaitz Jimenez
Arkaitz Jimenez

Reputation: 23168

That should be enough for freeing the memory.

delete[] inStartup;

However, if you are going to contain it inside a function and its not very large you better use stack, it is faster and does not need freeing.

char inStartup[2];

Upvotes: 1

Related Questions