Base and derived class allocation - c++

In the code below, drvdCls derives from bseCls. This code compiles and runs as it is. I however find an issue here: newBse will get deallocated after Test() exits. Am I right?
bseCls* Test()
{
bseCls* newBse = new drvdCls();
drvdCls newDrvd;
newBse = &newDrvd;
return newBse;
}

The object originally pointed to by newBse will be leaked. When you assigned the address of newDrvd to newBse you are losing the pointer to the heap-allocated object, and you will not be able to delete it. This memory will be unusable until the process terminates.
Additionally, you are returning the address of a stack-allocated object as a pointer, which is bad for two reasons:
The object's destructor will have been called before the function returns, meaning you would be using a pointer to a destructed object.
The memory allocated for the object lives on the stack and will almost certainly be clobbered by future function calls. At that point, your pointer will be point at something that is not a bseCls, but you will be using it as though it were.
If you use the pointer returned by this function, you are invoking undefined behavior and your program has license to do anything.

No, it won't be automatically deallocated. Every call to new must be matched by a call to delete. But that's not the only problem with your code, you're also returning the address of a local variable from the function.
newBse = &newDrvd; // memory leak, pointer to previously allocated object is lost
return newBse; // newDrvd is destroyed when function exits, so returned
// pointer points to invalid memory
What you probably want to do is
bseCls* Test()
{
return new drvdCls();
}
Now the caller must call delete on the returned pointer after using it. What you should do is
std::unique_ptr<bseCls> Test()
{
return new drvdCls();
}
Now the allocated object will automatically be deleted when the returned unique_ptr goes out of scope.

Related

Pointer is corrupting data for no good reason in C++ [duplicate]

I know this is pretty common question, but still new for me!
I don't understand concept of dangling pointer, was googling around, and writing test methods to find one.
I just wonder is this a dangling pointer? As whatever example I found was returning something, here I'm trying something similar!
Thanks!
void foo(const std::string name)
{
// will it be Dangling pointer?!, with comments/Answer
// it could be if in new_foo, I store name into Global.
// Why?! And what is safe then?
new_foo(name.c_str());
}
void new_foo(const char* name)
{
// print name or do something with name...
}
A dangling pointer is a pointer that points to invalid data or to data which is not valid anymore, for example:
Class *object = new Class();
Class *object2 = object;
delete object;
object = nullptr;
// now object2 points to something which is not valid anymore
This can occur even in stack allocated objects:
Object *method() {
Object object;
return &object;
}
Object *object2 = method();
// object2 points to an object which has been removed from stack after exiting the function
The pointer returned by c_str may become invalid if the string is modified afterwards or destroyed. In your example you don't seem to modify it, but since it's not clear what you are going to do with const char *name it's impossible to know it your code is inherently safe or not.
For example, if you store the pointer somewhere and then the corresponding string is destroyed, the pointer becomes invalid. If you use const char *name just in the scope of new_foo (for example, for printing purposes) then the pointer will remain valid.
A dangling pointer is a (non-NULL) pointer which points to unallocated (already freed) memory area.
The above example should be correct given that the string is not modified through new_foo.
Taken from here. Although, even if this is for C, it is the same for C++.
Dangling Pointer
When a pointer is pointing at the memory address of a variable but after some time that variable is deleted from that memory location while the pointer is still pointing to it, then such a pointer is known as a dangling pointer and this problem is known as the dangling pointer problem.
Initially
Later
Example
#include<stdio.h>
int *call();
int main() {
int *ptr;
ptr = call();
fflush(stdin);
printf("%d", *ptr);
return 0;
}
int * call() {
int x=25;
++x;
return &x;
}
Its output will be garbage because the variable x is a local variable. Its scope and lifetime are within the function call hence after returning the address of x variable x becomes dead and the pointer is still pointing to that location.
As a matter of style, I explain a dangling pointer as "a pointer which still exists, even though the object it pointed to no longer exists".
In your case, the pointer name exists for a shorter period that the object that it points to. So it's never dangling.
Inside common C++ classes, pointers dangle for a very short period, inside destructors. That's because the delete statement is before the last } of the destructor, while the pointer itself ceases to exist at the last }. If you don't want to worry about this, use e.g. unique_ptr<T>. The T* pointer will dangle for a very short time inside the unique_ptr::~unique_ptr destructor, which is perfectly safe.
Dangling pointers is a situation where you have valid pointers in the stack, but it is pointing to invalid memory. You might end up in this situation when you deallocate the heap memory before the pointers in stack deallocated.
This is a security issue. Because when you deallocate a memory, we are informing Operating System, that we no longer need this section of memory. So OS will mark that piece of memory as ready to allocate and allocate to other applications when they request for memory.
Usually, in C++, memory allocated and deallocated through a general pattern. Constructor in a class gets invoked when a class initialised and this is the right place to allocate memory in heap.Destructor will be invoked when the class instance goes out of scope, and this is the right place to deallocate memory from heap. Assume we already created a class that does allocation and deallocation of memory in constructor and destructor respectively.
int main() {
SomeClass pointer1 = SomeClass();
SomeClass pointer2 = pointer1;
}
In the above example code, there are two variables declared but both holding the same value. When the constructor invoked, it allocates a heap memory. Then we are declaring one more variable and assigning the same value. In C++ usually, when you assign a value of complex type, it does a shallow copy (unless you explicitly implemented copy constructor) instead of deep copy. That means the only pointer gets copied in Stack, but not the heap memory. Actually it is not recommended to copy heap memory for performance reasons. Now the final memory layout looks like that we have two pointers pointing to the same heap memory.
Now when the function is done with execution, local variables goes out of scope and it invokes destructor. First, pointer2 invokes destructor that deallocates the heap memory. At this point, pointer1 becomes dangling pointer. It points to a memory that is already deallocated.
From this example, we understood that the primary cause of dangling pointer is having multiple owners for the same resource. Because when one pointer deallocates memory other pointers became dangling pointers.
//Declaring two pointer variables to int
int * ptr1;
int * ptr2;
// Allocating dynamic memory in the heap
ptr1 = new int;
ptr2 = ptr1; // Having both pointers to point same dynamic memory location
//deleting the dynamic memory location
delete ptr1;
ptr1 = nullptr;
//ptr2 is still pointing the already deleted memory location
//We call ptr2 is a dangling pointer
Dangling Pointer and dangling pointer problem
If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location.
That pointer is called as dangling pointer and the problem that arises at that time is called as dangling pointer problem.
Here are some examples: Dangling Pointer and dangling pointer problem

Return value in a function not working? [duplicate]

I know this is pretty common question, but still new for me!
I don't understand concept of dangling pointer, was googling around, and writing test methods to find one.
I just wonder is this a dangling pointer? As whatever example I found was returning something, here I'm trying something similar!
Thanks!
void foo(const std::string name)
{
// will it be Dangling pointer?!, with comments/Answer
// it could be if in new_foo, I store name into Global.
// Why?! And what is safe then?
new_foo(name.c_str());
}
void new_foo(const char* name)
{
// print name or do something with name...
}
A dangling pointer is a pointer that points to invalid data or to data which is not valid anymore, for example:
Class *object = new Class();
Class *object2 = object;
delete object;
object = nullptr;
// now object2 points to something which is not valid anymore
This can occur even in stack allocated objects:
Object *method() {
Object object;
return &object;
}
Object *object2 = method();
// object2 points to an object which has been removed from stack after exiting the function
The pointer returned by c_str may become invalid if the string is modified afterwards or destroyed. In your example you don't seem to modify it, but since it's not clear what you are going to do with const char *name it's impossible to know it your code is inherently safe or not.
For example, if you store the pointer somewhere and then the corresponding string is destroyed, the pointer becomes invalid. If you use const char *name just in the scope of new_foo (for example, for printing purposes) then the pointer will remain valid.
A dangling pointer is a (non-NULL) pointer which points to unallocated (already freed) memory area.
The above example should be correct given that the string is not modified through new_foo.
Taken from here. Although, even if this is for C, it is the same for C++.
Dangling Pointer
When a pointer is pointing at the memory address of a variable but after some time that variable is deleted from that memory location while the pointer is still pointing to it, then such a pointer is known as a dangling pointer and this problem is known as the dangling pointer problem.
Initially
Later
Example
#include<stdio.h>
int *call();
int main() {
int *ptr;
ptr = call();
fflush(stdin);
printf("%d", *ptr);
return 0;
}
int * call() {
int x=25;
++x;
return &x;
}
Its output will be garbage because the variable x is a local variable. Its scope and lifetime are within the function call hence after returning the address of x variable x becomes dead and the pointer is still pointing to that location.
As a matter of style, I explain a dangling pointer as "a pointer which still exists, even though the object it pointed to no longer exists".
In your case, the pointer name exists for a shorter period that the object that it points to. So it's never dangling.
Inside common C++ classes, pointers dangle for a very short period, inside destructors. That's because the delete statement is before the last } of the destructor, while the pointer itself ceases to exist at the last }. If you don't want to worry about this, use e.g. unique_ptr<T>. The T* pointer will dangle for a very short time inside the unique_ptr::~unique_ptr destructor, which is perfectly safe.
Dangling pointers is a situation where you have valid pointers in the stack, but it is pointing to invalid memory. You might end up in this situation when you deallocate the heap memory before the pointers in stack deallocated.
This is a security issue. Because when you deallocate a memory, we are informing Operating System, that we no longer need this section of memory. So OS will mark that piece of memory as ready to allocate and allocate to other applications when they request for memory.
Usually, in C++, memory allocated and deallocated through a general pattern. Constructor in a class gets invoked when a class initialised and this is the right place to allocate memory in heap.Destructor will be invoked when the class instance goes out of scope, and this is the right place to deallocate memory from heap. Assume we already created a class that does allocation and deallocation of memory in constructor and destructor respectively.
int main() {
SomeClass pointer1 = SomeClass();
SomeClass pointer2 = pointer1;
}
In the above example code, there are two variables declared but both holding the same value. When the constructor invoked, it allocates a heap memory. Then we are declaring one more variable and assigning the same value. In C++ usually, when you assign a value of complex type, it does a shallow copy (unless you explicitly implemented copy constructor) instead of deep copy. That means the only pointer gets copied in Stack, but not the heap memory. Actually it is not recommended to copy heap memory for performance reasons. Now the final memory layout looks like that we have two pointers pointing to the same heap memory.
Now when the function is done with execution, local variables goes out of scope and it invokes destructor. First, pointer2 invokes destructor that deallocates the heap memory. At this point, pointer1 becomes dangling pointer. It points to a memory that is already deallocated.
From this example, we understood that the primary cause of dangling pointer is having multiple owners for the same resource. Because when one pointer deallocates memory other pointers became dangling pointers.
//Declaring two pointer variables to int
int * ptr1;
int * ptr2;
// Allocating dynamic memory in the heap
ptr1 = new int;
ptr2 = ptr1; // Having both pointers to point same dynamic memory location
//deleting the dynamic memory location
delete ptr1;
ptr1 = nullptr;
//ptr2 is still pointing the already deleted memory location
//We call ptr2 is a dangling pointer
Dangling Pointer and dangling pointer problem
If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location.
That pointer is called as dangling pointer and the problem that arises at that time is called as dangling pointer problem.
Here are some examples: Dangling Pointer and dangling pointer problem

C++ automatic memory: When is it deallocated?

I am having a hard time getting used to the way C++ handles dynamic and automatic memeory. My question:
Can a pointer, that points to an automatic allocated instance, keep that instance from deallocation even after the scope of the instanciation has been left?
In this post I read that all pointers pointing to dealloc memory are invalid. But is this guy talking about the behaviour after a manual dealloc or an automatic dealloc?
This is an example:
int main(){
UiTreeRecord child = UiTreeRecord::UiTreeRecord();
createSomeScope(child);
//Does child still have a valid parent?
//Or does parent point to a piece of memory that has been deallocated?
}
void createSomeScope(const UiTreeRecord& child){
UiTreeRecord root = UiTreeRecord::UiTreeRecord();
child.attachParent(root);
}
void UiTreeRecord::attachParent(UiTreeRecord& newParent) {
if(parent != nullptr) {
detachParent();
}
parent = &newParent;
}
automatic memory: When is it deallocated?
When the variable goes out of scope. Or in the case of automatic member variable, when the owning object is destroyed.
Can a pointer, that points to an automatic allocated instance, keep that instance from deallocation even after the scope of the instanciation has been left?
No, it can't. The pointer simply keeps pointing at the memory that is now invalid. Pointers and references to a destroyed object always become invalid regardless of the way the object was destroyed - be it automatic, dynamic or static deallocation.
In your example, root is deallocated at the end of createSomeScope and the pointer that you assigned in UiTreeRecord::attachParent becomes invalid.
It is potentially dangerous to do stuff like this. Either use * or use &, but don't use the pointer of a reference as the reference might get invalidated like in your case. In your example you create an instance first, then pass it as reference to attachParent(), then convert it to a pointer but the instance will be deallocated when createSomeScope() returns, thus your pointer becomes invalid.
void createSomeScope(const UiTreeRecord& child){
UiTreeRecord root = UiTreeRecord::UiTreeRecord();
child.attachParent(root);
}
root is invalid immediately after the function is ends and controlling the deallocation is not possible afaik. Memory might be freed at different "times" depending on code optimizations etc.

object created in function, is it saved on stack or on heap?

I am using c++ specifically:
when I create an object in a function, will this object be saved on the stack or on the heap?
reason I am asking is since I need to save a pointer to an object, and the only place the object can be created is within functions, so if I have a pointer to that object and the method finishes, the pointer might be pointing to garbage after.
--> if I add a pointer to the object to a list (which is a member of the class) and then the method finishes I might have the element in the list pointing to garbage.
so again - when the object is created in a method, is it saved on the stack (where it will be irrelevant after the function ends) or is it saved on the heap (therefore I can point to it without causing any issues..)?
example:
class blah{
private:
list<*blee> b;
public:
void addBlee() {
blee b;
blee* bp = &b;
list.push_front(bp);
}
}
you can ignore syntax issues -- the above is just to understand the concept and dilemma...
Thanks all!
Keep in mind following thing: the object is NEVER created in the heap (more correctly called 'dynamic storage' in C++) unless explicitly allocated on the heap using new operator or malloc variant.
Everything else is either stack/register (which in C++ should be called 'automatic storage') or a a statically allocated variable. An example of statically allocated variables are global variables in your program, variables local to the function which are declared static or static data members of classess.
You also need to very clear disntguish between a pointer and the object itself. In the following single line:
void foo() {
int* i = new int(42);
}
int is allocated dynamically (on the heap), while pointer to that allocated int has an automatic storage (stack or register). As a result, once foo() exits, the pointer is obliterated, but the dynamically allocated object remains without any means to access it. This is called classic memory leak.
Heap is the segment where dynamic memory allocation usually takes place so when ever you explicitly allocate memory to anything in a program you have given it memory from the heap segment.
Obj yo = new Obj; //something like this.
Stack is the another segment where automatic variables are stored, along with information that is saved each time a function is called.
Like when we declare:
*int* variable;
It will be on the stack and its validity is only till a particular function exits, whereas variables, objects etc on the heap remain there till main() finishes.
void addBlee() {
blee b; // this is created on the stack
blee* bp = &b;
list.push_front(bp); // this is a pointer to that object
} // after this brace b no longer exists, hence you have a dangling pointer
Do this instead:
list.push_front(new blee); // this is created on the heap and
// therefore it's lifetime is until you call
// delete on it`

Creating variable on heap and return the same variable

Hi i have few doubt related to heap variable...
I want to write a function as below ->
struct test
{
int x;
int y;
};
test* fun()
{
test *ptr = new test;
return ptr;
}
My doubt is returning a heap variable once it will go out of scope it will lost its value.
There is definitely a memory leak.(As heap variable is not deleted.)
So how can i design such kind of function.
Dynamically allocated objects (what you call heap variables) do not get destroyed at the end of the scope in which they were created. That's the whole point of dynamic allocation. While the test object is dynamically allocated, the pointer ptr is not - it will be destroyed when it goes out of scope. But that's okay! You copy the value of the pointer out of the function and this copy still points at the test object. The test object is still there. The function you've written is fine, but it isn't exactly good style.
Yes, there is a memory leak if nobody ever does delete on a pointer to the test object you created. That's a problem with returning raw pointers like this. You have to trust the caller to delete the object you're creating:
void caller()
{
test* p = fun();
// Caller must remember to do this:
delete p;
}
A common C-style way of doing this (which is definitely not recommended in C++) is to have a create_test and destroy_test pair of functions. This still puts the same responsibility on the caller:
void caller()
{
test* p = create_test();
// Caller must remember to do this:
destroy_test(p);
}
The best way to get around this is to not use dynamic allocation. Just create a test object on the stack and copy it (or move it) out of the function:
test fun()
{
test t;
return t;
}
If you need dynamic allocation, then you should use a smart pointer. Specifically, the unique_ptr type is what you want here:
std::unique_ptr<test> fun()
{
return std::unique_ptr<test>(new test());
}
The calling function can then handle the unique_ptr without having to worry about doing delete on it. When the unique_ptr goes out of scope, it will automatically delete the test object you created. The caller can however pass it elsewhere if it wants some other function to have the object.
You are not returning a heap variable, you are returning a value of a stack variable that holds a pointer to the heap. The stack variable goes out of scope; the memory pointed to by the pointer is in the heap - it never goes out of scope.
There will be a memory leak unless you release the memory in the caller.
My doubt is [that] returning a heap variable once it will go out of scope it will lo[se] its value.
No worry, because since you're returing the pointer by value; so the pointer will go out of scope, but since you're returning the memory that it points to, there is no memory leak (only if we can rely on the caller to delete it).
However, if we had returned the pointer by reference then we would have a problem:
test*& fun() // note the & (reference)
{
test *ptr = new test;
return ptr;
}
Here you're returning a reference to a temporary. When the variable goes out of scope you will be using an object that doesn't exist. This is why you can't return temporaries by reference.
My doubt is returning a heap variable once it will go out of scope it will lost its value.
No heap variable does not go out of scope as do go stack variables...
There is definitely a memory leak.(As heap variable is not deleted.)
Yes we have to free memory allocated on heap by ourself, otherwise there is memory leak...
I would suggest to read some tutorial related to it.