dynamic and automatic duration

Im practicing my skill in network programming using SFML.
but ive got a c++ problem kicking me.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::vector<sf::TcpSocket*> socks;

void func()
{
   sf::TcpSocket socket; 
   //....
   socks.push_back(&socket);
}

int main()
{
   func();
   std::cout << socks[0].getRemoteAddress(); // outputs NULL
}


and
1
2
3
4
5
6
7
8
9
10
11
12
std::vector<sf::TcpSocket*> socks;
void func()
{
  sf::TcpSocket* socket = new sf::TcpSocket;
  //....
  socks.push_back(socket);
}
int main()
{
 func();
 std::cout << socks[0].getRemoteAddress(); // outputs the expected output (the address)
}


so i dont know how that happens.
First snippet

line 8: socket is allocated on the stack and goes out of scope. You've pushed the address of it onto the vector, but that address now points to garbage.

Second snippet

Line 4; You've allocated socket from the heap so no worries about it going out of scope. This is the correct way to do it* Don't forget that anything you allocate from the heap, you also need to delete from the heap or you're going to have a memory leak.

* = A better approach is to use smart pointers so that the memory and the socket are automatically cleaned up.








that was a fast reply

got the point, it makes sense

in the second snippet, i thought that after the call to func();
memory leak will happen, can you tell me what happens to socket after line 10?

and does poppoing back the socks will delete the socket? if not where will i delete the socket?


ive read about smart pointers, they are very powerful

Last edited on
can you tell me what happens to socket after line 10?

Nothing. socket remains allocated on the heap.

and does popping back the socks will delete the socket?

No, it won't. Popping the vector will only delete the pointers. Any sockets that were allocated remain allocated unless you're using smart pointers in the vector.

1
2
3
// After line 11
  delete socks[0];    // delete the socket
  socks[0].erase();  // remove the pointer to the socket 


If you were using smart pointers, any sockets would be released when the socks vector goes out of scope at the end of the program when globals are unwound.


Last edited on
Topic archived. No new replies allowed.