Renew a pointer? - c++

Is it a thing not do to, or is it right? The fact is to use new many times on one pointer:
double * a;
a=new double (5);
cout<<*a<<endl;
a=new double(10);
cout<<*a;
delete a;
Thanks.
SOLUTION:
So one possible solution is?!
double * a;
a=new double (5);
cout<<*a<<endl;
delete a;
a=new double(10);
cout<<*a;
delete a;
In case we don't know if the pointer a point to empty cell, it's possible to use NULL pointer:
double * a=0;
//... the code use *a to allocate or not some informations
delete a;
// ... the code continues with the possibility of allocate again using *a.

In answer to your follow up question, (how do you make sure you're not deleting a null pointer): It doesn't matter. delete null does nothing.
It's better to write your code in a way that you know the state at any point: only assign pointers once. If you really want to use the idiom in your question, use a smart pointer (which will do the deletion for you as it gets reset or goes out of scope):
std::auto_ptr a;
a.reset(new double(5));
cout << *a << endl;
a.reset(new double(10));
cout << *a << endl;
// no need to call delete at all. std::auto_ptrs destructor will do it for you.

It's not okay - the first allocated memory will leak. But the main reason is that it's not idiomatic C++. What's wrong with plain old
double a;
a = 5;
cout << a << endl;
a = 10;
cout << a;

No, that will cause a memory leak. Every new needs a corresponding delete.

It is OK. Because a pointer can point to what it wants. So a double* p can point to any objects with type double.
However, in your specific situation, it is not perfectly OK, because you have newed a block of memory and then let the pointer change its target. The old 5 memory block has no pointer pointed to and you cannot access it anymore; however it still occupy a block of memory. This is considered as memory leak.
In this case, you may want to use something like
std::shared_ptr<double> p(new(10.0));
and then you can renew it to
p.reset(new(5.0));

Before you do a=new double(10); you need to delete a; first. Otherwise, you'll end up with a small memory leak, seeing as you requested the memory and then never freed it. Your code should look like this:
double *a = new double(5);
cout << *a << endl;
delete a; // note the delete
a = new double(10);
cout << *a;
delete a;

Related

About delete in C++

I'm freshman in c++.
What's the difference between "delete a" and "delete b" ? Thanks a lot!
int* a = NULL ;
int* b = new int(10) ;
a = b;
delete a;//does the space of b free?
delete b;
ps:my bad!i dont mean delete a,b at same time,it's actually two ways of delete memery which i wanna ask.
Another question!
How to release the int allocated by the expression new int(10) in case 2?
//case 1: right
int *a= new int(10);
delete a;
//case 2:
int b = *new int(10); // how to release the int?
You called a single new, you need to a call a single delete. After a = b; you can delete either one. But you must delete only one. Deleting through either pointer will have the same effect. After the delete call, both variables will become invalid, pointing to freed memory.

Pointer to a vector

What is wrong with the following code
vector < double >* a;
a->push_back(25);
a->push_back(30);
a->push_back(15);
a->push_back(40);
cout << a->at(2) << endl;
It should print 15, but it prints nothing
a is a pointer but is not properly initialized... it must be like:
int main()
{
std::vector<double>* a = new std::vector<double>;
a->push_back(25);
a->push_back(30);
a->push_back(15);
a->push_back(40);
std::cout << a->at(2) << std::endl;
delete a;
return 0;
}
What is wrong ...?
You are using a pointer where an automatic duration value is more appropriate.
std::vector < double > a;
a.push_back(25);
a.push_back(30);
a.push_back(15);
a.push_back(40);
std::cout << a.at(2) << std::endl;
Your pointer wasn't initialized. Additionally, based on the answer by ΦXocę 웃 Пepeúpa ツ, make sure when you are working with pointers to use new/delete correctly. For every new keyword, there should be a delete. It is also good practice to avoid dangling pointers (pointers that do not reference anything) by setting them to NULL (as of C++11, it's recommended to use nullptr: NULL vs nullptr (Why was it replaced?) and What exactly is nullptr? questions offer some good explanations) when you are done.
However, in this case, I agree with Acorn. You shouldn't have to point to a vectorobject because of how it allocates memory. It should be sufficient to just use a vector for your solution.

c++ delete pointer and then access the value of it points to

I just learned pointer and delete pointer in class for C++. I tried this code by my own
# include<iostream>
using namespace std;
int main(){
int num = 10;
int *p = new int;
p = &num;
cout << *p << endl;
delete p;
cout << num << endl;
return 0;
}
After deleting the pointer p, I cannot print the value of num. But if I delete p at the very end of the program, cout << num << endl; will give me 10. Anyone knows where I did run?
You first leaked a pointer
int *p = new int;
p = &num; // You just leaked the above int
then illegally deleted something you did not new
delete p; // p points to num, which you did not new
You have already received a couple of good answers that point out the mistake, but I read a deeper misunderstanding of the allocation and deallocation of heap vs stack variables.
I realised this has become a pretty long post, so maybe if people think it is useful I should put it as a community Wiki somewhere. Hopefully it clarifies some of your confusion though.
Stack
The stack is a limited and fixed size storage. Local variables will be created here if you don't specify otherwise, and they will be automatically cleaned up when they are no longer needed. That means you don't have to explicitly allocate them - they will start existing the moment you declare them. Also you don't have to deallocate them - they will die when they fall out of scope, loosely speaking: when you reach the end brace of the block they are defined in.
int main() {
int a; // variable a is born here
a = 3;
a++;
} // a goes out of scope and is destroyed here
Pointers
A pointer is just a variable, but instead of an int which holds a whole number or a bool which holds a true/false value or a double which holds a floating point, a pointer holds a memory address. You can request the address of a stack variable using the address operator &:
{
int a = 3, b = 4;
int* p = &a; // p's value is the address of b, e.g. 0x89f2ec42
p = &b; // p now holds the address of b, e.g. 0x137f3ed0.
p++; // p now points one address space further, e.g. 0x137f3ed4
cout << p; // Prints 0x137f3ed4
} // Variables a, b and p go out of scope and die
Note that you should not assume that a and b are "next to" each other in memory, or that if p has a "used" address as its value then you can also read and write to the address at p + 1.
As you probably know, you can access the value at the address by using the pointer indirection operator, e.g.
int* p = &a; // Assume similar as above
*p = 8;
cout << a; // prints 8
cout << &a << p; // prints the address of a twice.
Note that even though I am using a pointer to point at another variable, I don't need to clean up anything: p is just another name for a, in a sense, and since both p and what it points to are cleaned up automatically there is nothing for me to do here.
Heap
The heap memory is a different kind of memory, which is in theory unlimited in size. You can create variables here, but you need to tell C++ explicitly that you want to do so. The way to do this is by calling the new operator, e.g. new int will create an integer on the heap and return the address. The only way you can do something sensible with the allocated memory, is save the address this gives you. The way you do this, is store it in a pointer:
int* heapPtr = new int;
and now you can use the pointer to access the memory:
*heapPtr = 3;
cout << heapPtr; // Will print the address of the allocated integer
cout << *heapPtr; // Will print the value at the address, i.e. 3
The thing is that variables created on the heap will keep on living, until you say you don't need them anymore. You do that by calling delete on the address you want to delete. E.g. if new gave you 0x12345678 that memory will be yours until you call delete 0x12345678. So before you exit your scope, you need to call
delete heapPtr;
and you will tell your system that the address 0x12345678 is available again for the next code that comes along and needs space on the heap.
Leaking memory
Now there is a danger here, and that is, that you may lose the handle. For example, consider the following:
void f() {
int* p = new int;
}
int main() {
f();
cout << "Uh oh...";
}
The function f creates a new integer on the heap. However, the pointer p in which you store the address is a local variable which is destroyed as soon as f exits. Once you are back in the main function, you suddenly have no idea anymore where the integer you allocated was living, so you have no way to call delete on it anymore. This means that - at least for the duration of your program - you will have memory that according to your operating system is occupied, so you cannot use it for anything else. If you do this too often, you may run out of memory even though you can't access any of it.
This is one of the errors you are making:
int* p = new int;
allocates a new integer on the heap and stores the address in p, but in the next line
p = &num;
you overwrite that with another address. At this point you lose track of the integer on the heap and you have created a memory leak.
Freeing memory
Aside from freeing memory not often enough (i.e. not instead of once), the other error you can make is freeing it too often. Or, to be more precise, you can make the error of accessing memory after you have told your OS you don't need it anymore. For example, consider the following:
int main() {
int* p = new int;
*p = 10;
delete p; // OK!
*p = 3; // Errr...
}
That last line is very wrong! You have just returned the memory allocated when you called delete, but the address is still stored in p. After you call delete, your OS is allowed to re-allocate the memory at any time - for example, immediately after another thread could call new double and get the same address. At that point, if you write *p = 3 you are therefore writing to memory that is no longer yours which may lead to disaster, if you happen to overwrite the location in memory where the nuke's launch codes are stored, or nothing may happen at all because the memory is never used for anything else before your program ends.
Always release your own memory, and nothing but your own memory
We have concluded the following: memory allocated on the stack is not yours to claim, and not yours to release. Memory allocated on the heap is yours to claim, but you must also release it once and only once.
The following examples are incorrect:
{
int a = 3;
int* p = &a;
delete a;
} // Uh oh... cannot clean up a because it is not ours anymore!
{
int* p = new int;
delete p;
*p = 3; // Uh oh, cannot touch this memory anymore!
delete p; // Uh oh, cannot touch this memory anymore!
}
Why does it print 10?
Well, to be honest, you were just "lucky" there. Actually, the way your operating system manages memory, is generally pretty lazy. When you tell it "I would like some memory" it doesn't zero it for you. That is why it is a bad idea to write
int main() {
int a;
a = a + 3;
cout << a;
}
You get allocated a variable a somewhere in the memory, but the value of a will be whatever was in that memory location. It might be zero, or some random number that depends on how the bits fell when you booted your computer. That is why you should always initialize the variable:
int a = 0;
Similarly, when you say "I don't need this memory" anymore, the OS doesn't zero it. That would be slow and unnecessary: all it needs to do is mark the memory as "free to be re-allocated". So if you give it back and access it immediately afterwards, the probability that it has not been re-allocated yet is pretty large. Therefore
int* p = new int;
*p = 10;
delete p;
cout << *p;
is not guaranteed to print 10. The address p is pointing to may have been (partially) taken (and initialized!) by someone else immediately after the delete. But if it hasn't, the memory will still contain the value 10 there so even though it isn't yours anymore, C++ will still allow you to access it. Basically, when you are using pointers, you are telling it "trust me, I'm a programmer - you don't need to do all kinds of slow checks to make sure I'm staying where I'm supposed to be, instead I'll be careful about that myself!"
using namespace std;
int main(){
int num = 10; // a) an int is created on stack
int *p = new int; // b) another int is allocated on heap
p = &num; // c) address of int from stack is assigned to p and the pointer
// allocated in b) is leaked: as nothing points to it anymore,
// it can't be deleted
cout << *p << endl;
delete p; // d) deleting a pointer that was not dynamically allocated
// and is pointing to stack.
cout << num << endl;
return 0;
}

delete[] and delete seems to behave alike

here if I use delete or delete[] the output is still 70. Can I know why?
#include<iostream>
using namespace std;
int main()
{
int* c = new int[100];
for(int i=0; i<98; i++)
{
c[i] = i;
}
cout<<c[70]<<endl;
delete[] c;
or
delete c;
cout<<c[70]<<endl; //outputs 70 even after delete[] or delete
return 0;
}
Accessing deleted memory is undefined behavior. Deleting with the wrong delete is also UB. Any further discussion is pointless in the sense that you cannot reliably expect any outcome.
In many cases, UB will just do the "correct" thing, but you need to be aware that this is completely "by chance" and could change with another compiler, another version of the same compiler, the weather... To get correct code, you need to avoid all cases of UB, even those that seemingly work.
Using new will just allocate some memory to your program and return a pointer pointing at the said memory address, reserving as much memory as needed for the datatype. When you use delete later, it "frees" the memory, but doesn't delete it's content. If you had an int with the value 70 stored at that address, it will still contain 70, until another application wants some memory, gets said address and puts another value in there.
If you use new to allocate memory for an array, you will reserve following blocks of memory until there are enough blocks for your specified array length.
Let's say you do the following:
int main() {
int* array = new int[10]; // array now points to the first block of the allocated memory
delete array; // since array points to the first block of the array, it will only free that block, but nothing else, causing a memory leak
delete[] array; // will free all memory allocated by the previous new
// Note that you should never free allocated memory twice, like in this code sample. Using delete on already freed memory is undefined behaviour!
]
Always use delete for single variables and delete[] for arrays.
A demonstration of your problem:
int main() {
int* c = new int[10]; // We allocate memory for an array of 10 ints
c[0] = 1; // We set the value of the first int inside the array to 1
delete[] c;
/*
* We free the previously allocated memory.
* Note that this does not delete the CONTENT of the memory!
* c does still point towards the first block of the array!
*/
std::cout << c[0];
/*
* Firstly, this is undefined behaviour (Accessing deallocated memory).
* However, this will output 1,
* unless some other process allocated the memory at the address
* and filled it with another value already. (Very unlikely)
*/
return 0;
}
If you want to delete / overwrite the content of the deleted memory, you can use std::memset.
Example:
#include <cstring>
int main() {
std::size_t length = 10;
int* c = new int[length];
c[0] = 1;
std::cout << c[0] << std::endl; // Will output 1
std::memset( c, 0, length ); // Fill the memory with 0 bytes
delete[] c; // Now we free the array's memory
std::cout << c[0] << std::endl; // Will output 0
}
As others pointed its undefined behaviour and anything can happen.
These can be easily caught with the help of tools like valgrind.

Do pointers always lead to memory leak or they are deleted when they go out of scope?

I'm studying c++ and I'm reading about pointers. I'm curious about the following scenarios:
Scenario 1:
If I'm not mistaken, if the user types -1, there will be a memory leak:
#include <iostream>
using namespace std;
int main(){
int *p = new int;
cout << "Please enter a number: ";
cin >> *p;
if (*p == -1){
cout << "Exiting...";
return 0;
}
cout << "You entered: " << *p << endl;
delete p;
return 0;
}
Scenario 2:
But what happens in the following code? From what I've read and correct me if I'm wrong, when declaring a pointer like in the second scenario the pointer gets cleared out once you are out of scope. So if the user doesn't enter -1, the *p will be auto-cleared?
#include <iostream>
using namespace std;
int main(){
int x;
int *p = &x;
cout << "Please enter a number: ";
cin >> *p;
if (*p == -1){
cout << "Exiting...";
return 0;
}
cout << "You entered: " << *p << endl;
return 0;
}
What happens if I enter -1 in the second scenario?
Do not focus on the fact that you are using pointers that much. Memory leaks are usually about memory that the pointer points to, not about the pointer itself.
In this code:
int x;
int *p = &x;
there is no memory leak since there is no memory that would require explicit deallocation (no memory that has been allocated dynamically). int x is a variable with automatic storage duration that will be cleaned up automatically when the execution goes out of scope and int *p = &x; is just a pointer that holds the address of the memory where x resides.
But you are right that in code like:
Resource* r = new Resource();
if (something) {
return -1;
}
delete r;
there is a memory leak since there is a return path (exit path) that doesn't free the allocated memory. Note that the same would happen if the exception would be thrown instead of return being called... ensuring that all resources are freed properly is one of the main reasons why you should learn more about smart pointers, the RAII idiom and try to prefer objects with automatic storage duration over dynamically allocated ones.
In the second scenario, everything's fine.
Indeed, you haven't allocated memory (while you did in the first scenario). In the first case, the pointer "holds" the memory you allocated through new. In the second case, it points to a local variable with automatic-storage duration (i.e. it will be removed when going out of scope).
Simple rule: If you used new you must use delete (unless you're using a smart pointer). In the first scenario, if you type -1, you end up with one new and zero delete, which yields a memory leak. In the second case, you haven't allocated anything, the pointer points to memory that is already managed.
In the second scenario you do not allocate memory so you should not bother about some memory leak. You have to use delete or delete[] if you explicitly allocate memory with new or new for arrays.
In the second scenario p points to local variable x. It is the compiler that allocated memory for x in stack. So it is the compiler that properly will free this memory after x will be out of its scope.
In the first main, you dynamically allocating the int and manually delete it when exiting from main. However, if int is equal to -1, you do not delete it and return so that's why you have a memory leak.
In second example, the int is allocated on the stack and you're taking the address of it. When main returns, the int is deallocated automatically. If you tried to call delete on it in the main, you would get a crash.