Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Consider the following code:
struct A {
int someInt;
};
A *a = new A;
A *b;
delete a; // ok
delete b; // crash
It crashes, but I don't know why. I thought deleting null pointers is a no-op.
Do I even need to delete structs? Is it bad practice to create structs on the heap? Is it better to create them on the stack?
Deleting null pointers is a no-op, yes, so if b were a null pointer then you'd be fine.
But it's not. It's an uninitialised variable with an indeterminate value.
Here's a null pointer:
A* b = nullptr;
(If you write A* b; at global scope, or if you write static A* b; in a function, or if you are defining a static class member, then b has static storage duration and is automatically zero-initialised for you; this is the one exception to the rule.)
And, yes, you should avoid dynamic allocation where possible — using it for no good reason complicates your code for, well, for no good reason.
b is a uninitialized pointer. There is nothing to delete.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Let's say I have an array a which holds pointers to objects of a class B. Let's say a[0] points to object c.
If I now set a[0] = nullptr, will the destructor of c be called and thus c destroyed if c was constructed on the stack and if a[0] was the only thing referencing c.
If you refer to regular pointers (Obj* ptr) so c's d'tor would not be called because of the assignment. It might be called if there's a code like -
... // Some code and initialization before
{
Obj c;
a[0] = &c;
a[0] = NULL; //c isn't affected in any way by this assignment
} //End of scope. **c's d'tor is called here**
Although, if c was allocated on the heap, it's memory would have leaked
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I know if I create a pointer in the header file, I should always delete it when the destructor is being called, but what about if I create a pointer inside of a function. I know basic variables get destroyed at the end of the block, is it the same for pointers?
For example:
Class::Function()
{
int i = 3; // This gets destroyed after the function ends
int* j = 5; // What about this? Do I have to delete it somewhere to keep from a leak?
}
If I initialize j inside of the constructor, I would say delete j; to prevent leaks, etc. Is there something I should do in this case?
Assigning int value to pointer
int* j = 5;
is illegal because you are storing int to int*. Anyway you can cast it
int* j = reinterpret_cast<int*>( 5 );
but dereferencing this pointer would lead to undefined behavior, since you dont know where does that pointer point.
You should init pointers like that
int* j = nullptr;
Since c++11 you cant create instance of nullptr_t and assign it.
nullptr_t initPointer;
int* j = initPointer;
If you dont use new operator to assign memory to pointer, you can't delete this pointer, it would lead to undefined behavior. Otherwise if you use new you need matching delete or you would get memory leak. If you want to check your program have memory leaks, check this thread and choose one tool. I can recommend valgrind.
Every call to new needs a matching call to delete. If you have more new's than delete's, you get memory leaks. If the opposite, you get double deletes. In your case, if you never called new, then there's no need for delete!
There are tools out there to help match your new's and deletes. My personal favorite is cppcheck. It's super quick and easy to use, and it runs on the c++ source code! It generally does a good job at catching unmatched new and delete calls.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
comming from other programming language why can't I do this in c++:
myClass mc = new myClass();
it seems that it suffices to just write:
myClass mc;
but then what if I want to use make mc be a new instance of myClass and dump the existing one?
comming from other programming language why can't I do this in c++:
Because in C++ to initilize variable types on the left and right side of = must be compatible. In your case:
myClass mc = new myClass();
mc has type myClass and expression on the right has type myClass *. So you either need to change left side to:
myClass *mc = new myClass();
or right side to:
myClass mc = myClass();
to make both sides compatible. What implications it would have on class instance lifetime you should get from a C++ textbook.
new generates the object using dynamic memory from the heap. Your second line allocates it on the stack or in the data section. Please read about the differences of stack, heap and data section and the consequences for your application!
The new keyword means allocating heap memory to a pointer
int* pointer = new int(5);
This means that the int will be allocated on the heap as opposed to the stack.
When allocating memory with the new keyword you also have to delete it
delete pointer;
In your case, you should be able to assign a new value like so
mc = myClass();
without the new keyword.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
The following scenario seems very perplexing (this isn't a working code, just a much simplified version to illustrate the scenario, you get the idea):
class A {
private:
B* mb;
public:
A(B *b):mb(b) {}
~A() {
if(NULL != mb) { delete mb; }
}
}
int main(int argc, char **argv) {
B* b = new B();
A* a = new A(b);
delete A; //Everything is fine here
B b;
A* a = new A(&b);
//This will segfault, because b is allocated on the stack?
delete A;
B b;
//This segfaults as well because when it goes out of scope
//the program tries to delete b twice?
A a(&b);
}
If I am understanding this correctly, does it mean you could NEVER allocate such objects like A and B on stack any more when their class definition looks like this? Alternatively, I just simply don't define a destructor for A and then both A and B can be allocated on stack --- but this is probably bad and potentially gives memory leak? (If someday someone else looks at the code and decide to new A).
I thought the major advantage of C++ over Java would be you can avoid new and always deal with objects on stack to speed up, but what about this inflexibility of using an object either on stack or heap, as one like?
What's the deal here in C++? Which of the following two ways should one go then?
Define class A as above, and always new both A and B, while later remember to delete A only.
Define class A with no destructor, then always create A and B on stack and pass objects around by value (however there are cases I don't want a public copy constructor).
You are correct in assuming this segfaults because you're deleting an item that was allocated on the stack. You must only delete items that were allocated with new. Also, it's considered good practice to allocate and free memory within the same layer of code. If you must use object B in your code, it's better to create a copy of B:
class A {
private B* mb;
public:
A(B *b) {
mb = new B(*b); // calls B's copy constructor
}
~A() {
if(NULL != mb) { delete mb; }
}
}
Which of the following two ways should one go then?
Neither. Use option 3: Don't do this at all. You are right that an advantage of C++ is that you don't need to new and delete, but then you wrote a whole bunch of code that uses new and delete.
What problem are you trying to solve with this A? Undoubtedly there is a better way to solve the problem than with A.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
suppose for example this struct :
struct Point{
int x;
int y;
};
and I declared a pointer to this struct:
Point* p;
where're x and y of that p, heap or stack?
and Is that the same for classes?
where're x and y of that p, heap or stack?
Nowhere. You haven't created an object, just a pointer that could point to one.
If you create an automatic object on the stack, then that's where it will be:
Point point;
Point * p = &point;
If you create a dynamic object on the heap (officially called the free store), then that's where it will be:
Point * p = new Point; // Don't forget to delete it.
Is that the same for classes?
Yes; a struct is a class.
The answer to the question depends on what p points to. If it points to a stack-allocated structures, then p->x and p->y are on the stack. If it was obtained with new (or malloc), then they are on the heap.
Unlike some other languages, there is no difference in layout of C++ classes and structs. The difference between them is only in in default access restrictions: class members are private by default, while struct members are public.
It depends on how you initialize p. The variables x and y are in whatever p points to: if that is on the heap, they are on the heap; if it is on the stack, they are on the stack, and if p points to a static variable, they are neither.
Forget about heap and stack: those are implementation details for the compiler. What you're interested in is not where the bits are located, but the lifetime they might have.
And C++ doesn't really have structs: regardless of the keyword used (struct, class or union), what is declared is a class type. (Class types can be divided into two large categories, unions and non-union class types.)