This question already has answers here:
Code outside functions
(3 answers)
Closed 7 years ago.
I have a problem when using 'delete' operator. It is identified as a syntax error by VS2013 with Nov 2013 CTP compiler, giving the message: "expected a declaration". Here is the code:
int a = 1;
int* p = &a;
int* snj = new int[10];
delete p;
delete[] snj;
C++ doesn't let you write arbitrary expressions in the top-level like Python or other languages. You need to place your code in a function, probably main in this case:
int main()
{
int a = 1;
int* p = &a;
int* snj = new int[10];
delete p;
delete[] snj;
}
Note that using delete on a pointer which wasn't allocated using new is undefined behaviour.
Things like this are very basic and should be covered by your introductory book. If you don't have an introductory book, you should get one.
p points to the address of a. a is a local variable decalred on the stack. You can only call delete on dynalically allocated heap memory (Any variable created using the new keyword).
a is deleted automatically when it goes out of scope.
You should not delete p since it is not pointing to a heap element, it points to a stack element.
Related
This question already has answers here:
What happens to the pointer itself after delete? [duplicate]
(3 answers)
Why doesn't delete set the pointer to NULL?
(12 answers)
Closed 2 years ago.
Please have a look at this below code::
#include<iostream>
using namespace std;
int main()
{
int *ptr;
ptr = new int[100000];
cout<<"\n\n address = "<<ptr;
for(long int i=0;i<100000;i++)
*(ptr+i) = i+1;
delete []ptr;
cout<<"\n\n address = "<<ptr;
ptr = new int[5];
cout<<"\n\n address = "<<ptr;
return 0;
}
OUTPUT is:
address = 0xd42490
address = 0xd42490
address = 0xe919d0
Why,After delete []ptr; it is still pointing to its previous location(See the 2nd output).
delete[] is working just as it should. It ensures that destructors are called for the members of the array and marks the memory (internally) as available for re-use.
There's nothing in the C++ standard that says it has to zero the memory or return the memory to the OS or clear the variable holding the address you passed to it, etc.
Once you delete something, you know destructors have run and you also know that you are no longer allowed to look at (access) that memory. If you do anyway, there's no guarantee what you'll get (except UB).
A pointer is just like a cardboard sign saying "there's something over there". When you use delete on the pointer it destroys what's "over there", but it doesn't re-write the sign itself (the pointer), so the pointer still points to the same memory location it always did, but accessing that memory location is now forbidden.
delete [] has destroyed the array created dynamically at address ptr, but has not deleted the pointer itself.
A ptr = nullptr; command would perform that job, by indicating that ptr now points to nothing.
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 2 years ago.
Improve this question
I have 3 questions:
Q1. When we create the object using the new operator, following is the syntax:
pointer_variable = new data-type //To create an object
pointer_variable = new data-type(value); //To create an object with value
pointer_variable = new data-type[size]; //To create an array
Why always there is a pointer_variable on L.H.S?
Q2. What is the difference between declaring and assigning pointers with and without the new operator?
Consider the following code snippet and output to understand the question:
int a = 10, b=20;
int *p;
p = &a;
int *q = new int;
q = &b;
cout<<"P is: "<<p<<" : "<<*p<<endl<<"Q is: "<<q<<" : "<<*q<<endl;
Output of the above code:
P is: 0x61ff04 : 10
Q is: 0x61ff00 : 20
Q3. When we say, with a new operator we can dynamically allocate memory to the array at run time when we don't know the size of the array at compile time. We can do this without new operator as given below:
cout<<"Enter the size of an array"<<endl;
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=0;i<n;i++)
{
cout<<arr[i];
}
Then what is exactly the need to use the new operator for arrays?
Why always there is a pointer_variable on L.H.S?
Because new-expression results in a pointer.
What is the difference between declaring and assigning pointers with and without the new operator?
new-expression (not operator new) constructs a new object (and, optionally, allocates memory for it).
We can do this without new operator as given below
In fact, we cannot, according to the C++ Standard. Some compilers just allow this construct as a non-standard language extension.
Every good C++ book for beginners will explain these in more details.
in C++, a typical new expression allocates memory on the heap, and returns a pointer to that memory.
Re Q1: you can save the resulting pointer to a local variable for immediate use: pointer_variable = new int. But you don't have to do that: you could instead use it as an argument to a function: use_pointer(new int).
Re Q2: your code allocates an int on the heap, stores its pointer in local variable q, and immediately overwrites it with the address of local variable b. So what you have done here is write a small memory leak.
Re Q3: variable-sized array is a nonstandard extension to C++, so it will not necessarily work in another compiler. However, when it does work it is just another automatic variable: it will be automatically de-allocated for re-use when you leave the local scope. This is different from new allocations, which last until they are explicitly delete-ed.
This question already has answers here:
C++ delete - It deletes my objects but I can still access the data?
(13 answers)
Closed 4 years ago.
In the below code, memory is allocated for an integer and later a shallow copy is being made and finally delete is being called on it. How does it still print 23 as the output and why doesn't the delete call on q, cause a run time exception.
#include <iostream>
using namespace std;
int main() {
int* p = new int(23);
int* q = p;
delete p;
cout << *p << endl;
delete q;
return 0;
}
Undefined behaviour means anything can happen.
It might crash.
It might crash your car.
It might crash your brain.
It might crash Sagittarius A* into your brain.
It might crash your brain into your car, then crash them both into Sagittarius A*.
It might appear to work.
But it's still undefined.
Don't expect results.
This question already has answers here:
Can I delete[] a pointer that points into an allocated array, but not to the start of it?
(7 answers)
Why can't I delete pointer alone from an array of objects?
(4 answers)
Closed 5 years ago.
Consider, below program which gives runtime error. Point of this question is to understand memory view and management.
#include<iostream>
using namespace std;
int main(void) {
char* arr = new char[10];
char* ptr = NULL;
for(int i = 0; i < 10; i++) {
arr[i] = 'a';
}
cout << arr;
ptr = &arr[5];
delete ptr;
cout << arr;
return 0;
}
new allocates a block of memory. You can free that memory using delete, but you must pass the same address that was returned by new. That's how it works. You can't pass arbitrary addresses to delete.
Another option is to use malloc() and free(). These are older function but then you can also use realloc() to resize the memory. Then, if you want to delete part of the array, you can resize it to be smaller. BUT... you must still copy any data as needed to correctly form the resized array. That is not automatic.
This question already has answers here:
Calling delete on variable allocated on the stack
(12 answers)
Closed 9 years ago.
I am trying to understand how to delete a vector of pointers, and the pointed objects, in memory. I have started with a simple example, found in another thread, but I get "pointer being freed was not allocated" error.
What I am doing wrong?
#include <vector>
#include <algorithm>
#include <iostream>
int main(){
std::vector <int *> vec;
int a = 2;
int * b = &a;
int c = 3;
int * d = &c;
vec.push_back(b);
vec.push_back(d);
for (int i = 0; i < vec.size(); i++) {
delete vec[i];
}
vec.clear();
}
Only call delete on variables that were created with new
Check this link:
Calling delete on variable allocated on the stack
You're deallocating memory that was allocated on the stack with automatic storage. That's why you're getting errors.
Only delete things you allocated with new. RAII will take care of the rest.
When you do
int a = 2;
You are allocating a int on stack and anything on stack does not need to delete, it will be freed automatically once we left the scope it is declared. Therefore in your code, you are trying to free the same thing twice.
Whilst if you do
int* a = new int(2);
You will then allocate a int on heap, where data will not be deleted unless you explicitly call delete.
The bottom line is, new and delete should always be written in pairs.