C++ program's assertion failure due to deleting a pointer [duplicate] - c++

This question already has answers here:
Delete and invalid pointer
(2 answers)
Closed 8 years ago.
I have created an int variable.
Then I have assigned it to a pointer.
After that, I cout-ed it and then eventually I deleted.
What happens? The console pops up, but then immediately an error dialog box appear with the error Assertion Failure. Can any one explain why I receive the error? Here is the code:
int main()
{
int mainNum = 10;
int *numPt;
numPt = &mainNum;
cout << &numPt;
delete(numPt);
cout << endl << endl << endl; // this is to secure last newline char to be outputted.
cout << "---------------------------" << endl;
return 0;
}

You cannot delete stuff that is on the stack. You can only delete stuff that is on the heap (created by new). Otherwise all sorts of stuff will happen

Related

Deleted variable can still be accessed in c++? [duplicate]

This question already has answers here:
C++ delete - It deletes my objects but I can still access the data?
(13 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I created a simple project just to test how deleting variable works but i encountered a strange thing...
I created three int variables (1 stack based and 2 heap based) and when i deleted the heap variables using delete i still could access them. I can print them or change their value but how? Isn't delete supposed to permanently delete the variable from memory and also another question.... Why stack based variables can't be deleted using free() or delete?
Here is the (C++) script -
#include<iostream>
using namespace std;
void Stuff()
{
int* heap_int = (int*)malloc(4); //Heap based variable
*heap_int = 500;
int stack_int = 5; //Stack based variable
int* calloc_int = (int*)calloc(1,2); //Heap based variable
*calloc_int = 600;
std::cout << "Value (HeapInt) : " << *heap_int << "\n"; //Prints 500
std::cout << "Value (CallocInt) : " << *calloc_int << "\n"; //Prints 600
std::cout << "Value (StackInt) : " << stack_int << "\n"; //Prints 5
delete heap_int;
delete calloc_int;
//delete stack_int; (will not work)
std::cout << "\nValue after delete (HeapInt) : " << *heap_int << "\n"; //Still prints 500
std::cout << "Value after delete (CallocInt) : " << *calloc_int << "\n"; //Still Prints 600
std::cout << "Value after delete (StackInt) : " << stack_int << std::endl; //Prints 5
*heap_int = 82;
}
int main()
{
Stuff();
}
I heard in online tutorials that heap based variables only get freed if we used delete or free() (unlike stack variables who get freed automatically when their scope ends) then why can't i access an heap based variable out of scope like this...?
#include<iostream>
void Function()
{
int* variable = new int;
*variable = 6;
}
int main()
{
*variable = 9; //Error says "Use of Undeclared identifier variable"
}
Reading the contents of a free'd or deleted memory address is called undefined behavior.
delete heap_int;
std::cout << "\nValue after delete (HeapInt) : " << *heap_int << "\n"; //Still prints 500
You might still be able to see the previous value at a deleted address, but it's definitely not guaranteed. As soon as the next malloc/new happens (or technically at any time), the memory manager might re-use that address for another object and overwrite what's there.
And this:
*heap_int = 82;
Similarly, writing to a deleted address is even worse undefined behavior - chances are high you have corrupted your program's behavior in strange ways, or at best, a fast crash.
why can't i access an heap based variable out of scope like this...?
Because you can't access any variable that's not in your scope or the parent scope. In your case, code in main can only access variables in that function or variables declared at global scope. That's the whole point of scope!

Dereferencing returned pointer from thread causes; Segmentation fault: 11 [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 6 years ago.
I'm very new to c++ and programming with pointers. I was trying to pass an argument to a thread, add one to it, and thereafter return a pointer to this result. The main thread should just print the result pointed to by the returned pointer.
#include<stdio.h>
#include<pthread.h>
#include<iostream>
using namespace std;
void* calculator(void* _n) {
int* n = (int*) _n;
int* i;
int result = *n + 1;
i = &result;
return i;
}
int main(){
int input;
pthread_t calcThread;
void* exitStatus;
int* threadResult;
cout << "Input integer: " << endl;
cin >> input;
cout << "Init thread..." << endl;
pthread_create(&calcThread, NULL, calculator, &input);
pthread_join(calcThread, &exitStatus);
// Error around here?
threadResult = (int*) exitStatus;
cout << "Returned: " << *threadResult << endl;
}
The code compiles, but I get a segmentation fault when executing. My guess is that it has something to do with the cast i'm doing, but i can't figure out what.
Any help will be greatly appreciated!
i = &result;
You're returning a pointer to local variable. As soon as it goes out of scope, accessing it yields undefined behavior.

Printing struct value from a list using iterator [duplicate]

This question already has an answer here:
Error in Getting Value from Vector of Pairs
(1 answer)
Closed 7 years ago.
I am having trouble with printing values from my struct Pages. I am trying to print the value of segment in Pages from a list of pages. The assignSegments() method is assigning values to the variable segment. This is the error I am getting. ‘std::list::iterator’ has no member named ‘segment’
Here is the code I have so far. If you need more code from me just let me know.
Following code is in my main
Process child;
char c = 'A';
c = c+i;
child.letter = c;
assignSegments(child.childPages, child.letter, CreateRandomNumber());
for(list<Pages>::iterator iter = child.childPages.begin(); iter != child.childPages.end(); i++)
{
cout << *iter.segment << endl; // having trouble printing here
}
Here are my structs that I am using.
struct Pages
{
string segment;
char validBit;
int refByte;
Pages * pagePointer;
int* memoryPointer;
};
struct Process
{
char letter;
list<Pages> childPages;
};
I think cout << iter->segment << endl; is what you're looking for.
operator. has a higher precedence over operator*, so iter.segment will be evaluated first, obviously it's not what you want.
Reference for C++ Operator Precedence
you can change
cout << *iter.segment << endl;
to
cout << (*iter).segment << endl;
or just
cout << iter->segment << endl;

C++ setting char pointer to null [duplicate]

This question already has answers here:
unable to print char* pointing to 0
(4 answers)
Closed 9 years ago.
In Visual studio 2012, I was messing around with pointers, and I realized that this program kept crashing:
#include <iostream>
using std::cout;
using std::endl;
int main ()
{
const char* pointer = nullptr;
cout << "This is the value of pointer " << pointer << "." << endl;
return 0;
}
My intent was the set a pointer to nullptr, and then print the address. Even though the program compiles, it crashes during runtime. Can someone explain what is going on?
Also, what's the difference between pointer and *pointer?
You are using a const char* which, when used in std::cout's operator <<, is interpreted as a string.
Cast it to void* to see the pointer's value (the address it contains):
cout << "This the value of pointer " << (void*)pointer << "." << endl;
Or if you want to be pedantic:
cout << "This the value of pointer " << static_cast<void*>(pointer) << "." << endl;
LIVE EXAMPLE
Although you can do cout << "Pointer is " << (void*)pointer << ".\n"; as already been suggested I feel that in this case the "C way" of doing it is prettier (no casting) and more readable: printf("Pointer is %p\n",pointer);

Deleting a pointer to an automatic variable [duplicate]

This question already has an answer here:
What is the behavior of "delete" with stack objects? [duplicate]
(1 answer)
Closed 8 years ago.
Please look at this code
int i = 10; //line 1
int *p = &i; //line 2
delete p; //line 3
cout << "*p = " << *p << ", i = " << i << endl; //line 4
i = 20; //line 5
cout << "*p = " << *p << ", i = " << i << endl; //line 6
*p = 30; //line 7
cout << "*p = " << *p << ", i = " << i << endl; //line 8
What is the result of this code? Especially of line 3, 5 and 7? Do they invoke undefined behavior? What would be the output?
EDIT : I tried running it using g++, and it's compiling and running fine! I'm using MinGW on Windows 7.
What does Standard say in this context?
You can delete only a pointer if you have ever allocated it dynamically using new. In this case you have not allocated the pointer using new but simply defined and initialized it to point to a local variable of type int.
Invoking delete on a pointer not allocated dynamically using new is something called Undefined Behavior. In short, it means that anything on the earth can happen when such a code is executed and you can't complaint a bit to anyone on this planet.
delete p; is UB and so any further behavior can't be predicted or relied upon. You program might crash immediately or spend all your money or just exit from main() and pretend nothing happened.
Line 3 is definitely undefined behaviour, since you're trying to deleting memory at an address that is not on the heap.