0

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.

3
  • 2
    What is wrong with the way you have it? And better yet, just use the stack so you don't have to worry about it. Commented Nov 10, 2014 at 15:51
  • You can use shared_ptr<> if you want. Smart pointers are good for you. As @Cyber mentioned, there is nothing wrong with it unless you are intending to do something more with it (and tell us what). Commented Nov 10, 2014 at 15:51
  • When I call this function for second time, it crashes even when I have only those 3 lines in the code and everything else is commented hence I thought it could be memory issue Commented Nov 10, 2014 at 16:20

4 Answers 4

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

You could just use the new std::vector::data() function instead of &inStartup.at(0).
@sjdowling: Ah right, I keep forgetting about that one.
2

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
}

2 Comments

How will this work without a constant expression? eg if I have a variable instead of 2
In that case you might want to use dynamic allocation, but your example used a hard-coded constant (2) for the size.
1

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];

Comments

0

This is properly deleting the memory.

delete[] inStartup;

conjured up by

new []

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.