Assuming I have a pointer ptr and I allocate some space for that pointer. Now, if I have another pointer ptr2 and do this:
ptr2 = ptr;
Does this mean I allocate space for ptr2 or do I need to allocate for ptr2 by myself?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, depends what you mean by “allocate space for a pointer”.
For example:
allocates space for the pointer in automatic memory. The pointer doesn’t point to anything meaningful though. If you did:
you have space allocated in automatic memory for the pointer itself, and that pointer points to the memory allocated by
new int, which is in dynamic memory.If now you did:
you have some memory in automatic memory for
ptr2itself, but it will point to the same location in dynamic memory asptr.So in the end, you have allocated memory for 2
int*s in automatic storage, and for oneintin dynamic storage. The two pointers point to the same memory.The automatic memory is cleaned up automatically (duuh). You have to delete the dynamically allocated memory yourself:
Note that since the two point to the same location, so:
would yiled undefined behavior (so is illegal).
(this is all subject to optimizations, but, in principle, it goes down like this)