• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

noob C++ pointer question

eon

2[H]4U
Joined
Oct 11, 2003
Messages
2,218
Code:
void Obj::func()
{
int *a = new int(1);
p = a;
}
lets say p is a class int pointer variable, the address that p and a point to after func is run will not get deallocated after that method goes out of scope because there is no delete statement, correct?
 
Correct, basically all you have to remember is that a pointer just holds a memory location and you can change that memory location. That is exactly what are you doing but you are not realising the memory that was at the previous memory location.
 
ya i know if an address was previously allocated to p that it should be deallocated before reassign p, this was just a quick example as i sometimes get hypothetical pointer questions while i code
 
ya i know if an address was previously allocated to p that it should be deallocated before reassign p, this was just a quick example as i sometimes get hypothetical pointer questions while i code

When I do memory allocation, I try to keep itless complicated by not passing the pointer around too much.

However, unless I am mistaken, I think you're incorrect here. Also make sure your terms stay correct, otherwise you'll find it difficult to get help here sometimes (people are stickler to details, which is good). When you say an address was allocated to a pointer, you want to think of it as a chunk of memory was allocated, and the address to the beginning of this chunk was assigned to the pointer.

With that said, I want to point out:

Code:
...
int* p = new int(1);
int* a = new int(1);
p = a;

is not the same as:

Code:
...
int* p = new int(1);
delete[1] p;
int* a = new int(1);
p = a;


The memory allocated to p before the assignment will not be deallocated by simply reassigning. You must call delete.

I know you're not asking complex questions, but I think you would like to look up the topic of RAII (Resource Allocation is initialization)

Hope I helped some, good luck
 
Back
Top