Class objects destruction - pointers

In the following code I intentionally set a pointer, p, to NULL after deleting it so that the second object can't delete it again. However, I recieve the following error dialog in Microsoft Visual C++:
Debug Assertion Failed - Expression: _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse)
Full size image of the error dialog.
#include <iostream>
#include <string>
using namespace std;
class line{
public:
line();
~line();
int* p;
};
line::line(){
p = new int;
}
line::~line()
{
if (p != NULL)
{
delete p;
p = NULL;
}
}
int main()
{
line line1,
line2 = line1;
cout << line1.p << endl << line2.p;
cin.get();
return 0;
}

line1 and line2 are both holding a pointer.
You need to understand that line1.p is a separate variable toline2.p, even though they are pointing to the same address in memory.
Suppose that the line2 destructor is invoked first. It will set line2.p to NULL, but this will not alter the location that line1.p is pointing to.
When the line1 destructor is subsequently invoked, it will attempt to deallocate the already deallocated data that line1.p is pointing to, hence the Debug Assertion.

Related

Declaring a shared Pointer within a function produce a leaky memory behavior

I‘ve been trying to understand smart pointers, and as I understood, smart pointer will destroy themselves once they are not reachable through the code.
For this reason I was trying to implement a demonstration for this behavior:
#include<iostream>
#include<memory>
using namespace std;
void shared(){
cout<<"Shared Pointer:"<<endl;
shared_ptr<int> number = make_shared<int>(50);
cout<<*number<<endl;
cout<<number<<endl;
}
int main(){
int address;
shared();
cout<<"please enter the targeted address:"<<endl;
cin>>address;
int *pointer = (int *) address;
cout<<"we found this number: "<<*pointer<<endl;
}
output:
Shared Pointer:
50
0xf28c30
please enter the targeted address:
15895600 // I just converted the hexdecimal above to decimal number.
we found this number: 50
So I‘m able to retrieve the value 50 from outside the function shared(), by manually entering its address in the console.
Isn‘t supposed to be null or random number? If this is normal then how smartpointers are made to avoid memory leaks!?
P.S: doing the same test using a normal pointer will produce the same results unless we add delete pointer; (which is the expected behavior)
I appreciate any idea about this specific behavior.
To make sure that the memory was deleted it is better to test the smart pointers with a class
class Greeting {
public:
Greeting()
{
std::cout << "Hello" << std::endl;
}
~Greeting()
{
std::cout << "Bye" << std::endl;
}
};
void shared() {
shared_ptr<Greeting> var = make_shared<Greeting>();
}
int main() {
std::cout << "Start" << std::endl;
shared();
std::cout << "End" << std::endl;
}
You will get the following output:
Start //Start of the main
Hello // When creating the object (the resource)
Bye // **When destructing the object (the resource)**
End //End the main

qt bulk insert sqlite

For a qt/qml project im doing inserts into a database.
Because there is plenty of data to send (200+ inserts/sec) I want to do it in bulk.
The inserts are into different tables.
I have the queries already prepared.
I made one method that should commit the queries after it reached 100 queries.
//in the constructor i laready say mdb.transaction() for the first run.
bool DatabaseWriter::executeQuery(QString insertQuery)
{
queryCounter ++;
qDebug() << QString::number(queryCounter);
QSqlQuery query(mydb);
if(!query.exec(insertQuery))
{
qDebug("%s.", qPrintable(mydb.lastError().text()));
qDebug() << "Something went wrong while running " + insertQuery + " from the database";
return false;
}
if(queryCounter > 100)
{
qDebug() << "Should commit";
if(!mydb.commit())
{
qDebug() << "commit failed";
}
mydb.transaction();
queryCounter = 0;
}
return true;
}
But mydb.commit() returns false.
What is the proper way to do a bulk insert?
I also tried:
if(query != ""){
query_to_commit += query +";";
insert_counter ++;
if(insert_counter > 100)
{
dbWriter.executeQuery("BEGIN TRANSACTION; "+query_to_commit+ " COMMIT;");
insert_counter = 0;
query_to_commit = "";
CustomLogger::log("Running bulk insert");
}
}
which generates a bulk transaction that works fine when executing it in my sqlite databsase but not when I do it with my code, in my code I get: Driver not loaded Driver not loaded. I do not get this error when running a single insert query.
To keep it simple, how can I run e.g.:
INSERT INTO settings (name, x, y) VALUES('somename', 100, 20)
INSERT INTO different_table(bla, x, y) VALUES('bla', 100, 20)
In one go instead of doing it in two.
Or How can i execute:
BEGIN TRANSACTION;
INSERT INTO settings (name, x, y) VALUES('somename', 100, 20)
INSERT INTO different_table(bla, x, y) VALUES('bla', 100, 20)
COMMIT;
The main goals is to not write 200 times a second but just do it in one go, if i do it 200 times a second my gui is blocked/buggy (on the same thread I gues).
I made a seperate query thead, my header file:
#ifndef QUERYTHREAD_H
#define QUERYTHREAD_H
#include <QThreadPool>
#include <QString>
#include <QSqlQuery>
#include <QSqlDatabase>
class QueryThread : public QRunnable
{
QString query_to_run;
static int queryNumber;
public:
QueryThread(QString query_list);
void run();
};
#endif // QUERYTHREAD_H
my cpp file:
#include "querythread.h"
#include <QDebug>
#include <windows.h> // for Sleep
#include <QSqlError>
#include "customlogger.h"
#include "databasewriter.h"
int QueryThread::queryNumber = 1;
QueryThread::QueryThread(QString query)
{
this->query_to_run = query;
}
void QueryThread::run()
{
{
// Make sure to have a unique database connection name by using the a static counter.
QString connectionName = "connection_name_"+QString::number(queryNumber ++);
QSqlDatabase mydb = QSqlDatabase::addDatabase("QSQLITE", connectionName);
mydb.setDatabaseName(DatabaseWriter::dirPath);
if(!mydb.open()){
CustomLogger::log("Cant open DB");
return;
}
QSqlQuery query(mydb);
if(!query.exec(query_to_run))
{
CustomLogger::log(qPrintable(mydb.lastError().text()));
CustomLogger::log("Something went wrong while running query: " + query_to_run);
}
mydb.close();
}
QSqlDatabase::removeDatabase("QSQLITE");
}
I start a new query with:
QueryThread *queryThread = new QueryThread(insertQuery);
// QThreadPool takes ownership and deletes 'queryThread' automatically
QThreadPool::globalInstance()->start(queryThread);
This implementation runs the queries on a seperate thread of the ui thread. It opens a connection for each insert though, so im not sure if this solution does not cause performance issues. so far it looks ok with 1.600.000 inserts in 16 hours.
If your doing a lot of inserts make so to put you database in wal mode to avoid the database from being locked.

'this' pointer changes in c++11 lambda

I found a very strange problem with this pointer in c++11's lambda.
#include <string>
#include <iostream>
using namespace std;
#include <boost/signals2.hpp>
boost::signals2::signal<void()> sig;
struct out {
void print_something() {
cout << "something" << endl;
}
out() {
auto start = [&] {
cout << "this in start: " << this << endl;
this->print_something();
};
cout << "this in constructor: " << this << endl;
// sig.connect(start);
sig.connect([&] {
cout << "this in signal: " << this << endl;
start();
});
this->print_something();
}
};
int main() {
out o;
sig();
}
The code prints three this(s) pointer at different location. I was expecting that all the three this pointer should be the same value, but they are not. Here's the output:
this in constructor: 00F3FABB
something
this in signal: 00F3FABB
this in start: 00F3FB00
something
Question 1: Why is this in start has different value? How to correct it?
Question 2: Since the this in start is a different pointer, it shouldn't be able to call print_something(). I would expect a crash on this but it works fine. Why?
You capture start by reference, but the variable start and the contained lambda function get destroyed at the end of out().
Later the signal handler tries to call start(), but the lambda function doesn't exist anymore. Maybe the memory where its this was stored was overwritten in the mean time, causing unexpected output.
The call to print_something() doesn't crash despite of the invalid this because the function doesn't actually try to use this. The printing in the function is independent of this and the lookup of print_somethings address can happen at compile time so that calling the function doesn't access this at runtime.

Storing local dynamic_pointer_cast<>() in outer scope

In the following piece of code, I'm retrieving a shared_ptr<A> from a function. I then dynamically cast the pointer to a deriving class and store it in a shared_ptr<B>. The original pointer is not a nullptr.
shared_ptr<B> storage = nullptr;
if (...)
{
shared_ptr<A> definition = getSharedPointer();
// Store the lambda
storage = dynamic_pointer_cast<B>(definition);
}
I would expect the dynamic_pointer_cast and storage to storage to increase the total reference count to 2. Then, when I leave the scope of the if-statement, storage's reference count should be one.
Yet, when I tried to call a method on storage, I get a EXC_BAD_ACCESS, implying I'm reading in a deleted pointer.
storage->foo(...)->bar(...);
Is my logic wrong? Is this a bug in clang (can't imagine)?
EDIT
I seem to have found the error, which has nothing to do with the pointers. The function bar() actually gave the problem. If anyone ever reads this: the above code is perfectly valid.
This example works fine:
#include <memory>
using namespace std;
struct A {
virtual ~A() {}
};
struct B : A {};
shared_ptr<A> getSharedPointer() {
return make_shared<B>();
}
#include <iostream>
int main() {
shared_ptr<B> storage = nullptr;
if (true)
{
shared_ptr<A> definition = getSharedPointer();
// Store the lambda
storage = dynamic_pointer_cast<B>(definition);
}
cout << storage.get() << endl;
}
It would seem that your shared_ptr<A> is not pointing to a B and the result of the dynamic_pointer_cast is nullptr. Maybe a debugging statement would be helpful:
if (...)
{
shared_ptr<A> definition = getSharedPointer();
cerr << "as A: " << definition.get()
<< ", as B: " << dynamic_cast<B>(definition.get()) << endl;
// Store the lambda
storage = dynamic_pointer_cast<B>(definition);
}

Stack-recursion program problems

I am a novice C++ coder and obviously not very good at it. I am having an immense amount of trouble with this program.
I am getting syntax errors on my opening and closing parenthesis on my functions, syntax errors on my "<" in my header cpp file, and errors that I'm missing parenthesis.
My first stack is not recognized (main driver file) and in my StackType.cpp file - original is an "undeclared identifier".
Lastly, the left of Push must have class/struct/union - in my for loop when filling the first stack with the rings.
I apologize for all of these issues in advance. Any help you could give me would be greatly appreciated!
Thank you.
======================Stack Header================================
// File: StackType.h
// Stack template class definition.
// Dynamic array implementation
#ifndef StackType
#define StackType
template <class ItemType>
class StackType
{
private:
int ItemType;
ItemType *myStack; // pointer to dynamic array
int _top, _maxSize; // using underscores to remind that it's private
public:
StackType(int numRings = 50); // Constructor
StackType (const StackType<ItemType>&); // Copy Constructor
// Member Functions
void Push(ItemType); // Push
void Pop(ItemType &); // Pop
void stackTop(ItemType &) const; // retrieve top
bool stackIsEmpty() const; // Test for Empty stack
bool stackIsFull() const; // Test for Full stack
~StackType(); // Destructor
};
#endif
=====================Stack cpp file==================================
#include "StackType.h"
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
// Constructor with argument, size is numRings, limit is 50 (set in .h header)
template <class ItemType>
StackType<ItemType>::StackType()
{
_maxSize = numRings;
_top = -1;
}
// Copy Constructor
template <class ItemType>
StackType<ItemType>::StackType(const StackType<ItemType>& original :
_maxSize(original._maxSize), top(original._top)
{
myStack = new ItemType[_maxSize];
for (int i = 0; i <= top; i++) myStack[i] = original.myStack[i];
}
// Destructor
template <class ItemType>
StackType<ItemType>::~StackType()
{
delete [] myStack;
}
// Push
template <class ItemType>
void StackType<ItemType>::Push(StackType<ItemType> ringVal)
{
if(stackIsFull()) cout << "\t There is not enough available memory = the stack is
full!" << endl;
else myStack[++_top] = ringVal;
}
// Pop
template <class ItemType>
void StackType<ItemType>::Pop(StackType<ItemType> &ringVal)
{
if(stackIsEmpty()) cout << "\t The stack is empty!" << endl;
else ringVal = myStack[_top--];
}
// Retrieve stack top without removing it
template <class ItemType>
void StackType<ItemType>::stackTop(StackType<ItemType> &ringVal) const
{
if(stackIsEmpty()) cout << "The stack is empty!";
else ringVal = myStack[_top];
}
// Test for Empty stack
template <class ItemType>
bool StackType<ItemType>::stackIsEmpty() const
{
return (_top < 0);
}
// Test for Full stack
template <class ItemType>
bool StackType<class ItemType>::stackIsFull() const
{
return (_top >= (_maxSize - 1));
}
// end StackType.cpp
=========================Main Driver file=======================================
#include "StackType.h"
#ifdef _DEBUG
#include "StackType.cpp"
#endif // _DEBUG
#include <stack>
#include "StdAfx.h"
#include <iostream>
using namespace std;
// Global Variable - Counter to display the number of moves.
int count = 0;
class StackType;
// Functions Prototypes
void MoveRings(StackType<ItemType>&, StackType<ItemType>&);
// Function to move the rings
void Pegs(int D,StackType<ItemType>& b,StackType<ItemType>& e, StackType<ItemType>& h);
// This is a recursive function.
void Display (int, StackType <ItemType>& , StackType<ItemType>&, StackType<ItemType>&);
// Function to display the pegs
// Main - Driver File
int main()
{
// create 3 empty stacks
StackType<ItemType> FirstPeg; // Receiving an error that this is not identified
StackType<ItemType> EndPeg;
StackType<ItemType> HelperPeg;
// Number of rings.
int numRings;
cout << "\n\t *********** Rings to Pegs (Towers of Hanoi) ***********\n" << endl;
cout << "\t Please Enter the number of rings you want to play with: ";
// Input number of rings
cin >> numRings;
cout << endl;
while(numRings < 0 || isalpha(numRings)) // To make sure that the user did not
// enter an invalid number
{
cout << " Your entry is invalid. Please use only integers. Please re-
enter: ";
cin >> numRings;
cout << endl;
}
for(int i = 1; i <= numRings; i++)
// Fill the first peg with the number of rings.
{
FirstPeg.Push(i);
}
Pegs(int, StackType<ItemType>&, StackType<ItemType>&, StackType<ItemType>&);
// To call the recursive function that will move the rings
Display (int, StackType<ItemType>&, StackType<ItemType>&, StackType<ItemType>&);
// To call the display function
cin.clear();
cin.ignore('\n');
cin.get();
return 0;
}
// This function will move an ring from first peg to the second peg
void MoveRings(StackType<ItemType>& beg, StackType<ItemType>& theEnd) //End
{
int r; // disk will be removed from one stack and added to the other
beg.Pop(r);//pop from source
theEnd.Push(r);//and move to target
}
// This function displays the moves
void Display(int R, StackType<ItemType>& toBegin , StackType<ItemType>& toEnd,
StackType<ItemType>& toHelp)
{
StackType<int> B;// create temporarily first stack
StackType<int> E;// create temporarily End(End) stack
StackType<int> H;// create temporarily helper stack
for(int i = 1; i <= R; i++)
{
toBegin.Pop(i);//moves the ring from source
B.Push(i);//to the temporarily stack to display it
cout << "Beginning Peg:" << &B << endl;
toEnd.Pop(i);//moves the ring from source
E.Push(i);//to the temporarily stack to display it
cout << " End(Final) Peg: " << &E << endl;
toHelp.Pop(i);//moves the ring from source
H.Push(i);//to the temporarily stack to display it
cout << " Helper Peg:" << &H << endl;
}
}
//-------------------------------------------------------------------
void Pegs(int D,StackType<ItemType>& b,StackType<ItemType>& e,StackType<ItemType>& h)
// This is a recursive function.
{
if (D == 0) // The base
{
return 1;
}
else if(D == 1) // If there is only one ring, move this ring from the
// first peg to the end(final) peg
{
MoveRings(b, e); // moves the ring from the first to the end(final) peg
cout<<" Really? You have entered one ring..." << endl;
cout<<" It moves directly from the first peg to the End peg." << endl;
count++; // increment the number of moves
cout << "There has been " << count << " move. "<< endl;// display the
// number of moves
Display (D, b, e, h);
}
else if (D > 1) // a recursive function in order to move the rings
{
Pegs(D - 1, b, e, h); // to move N-1 rings from the first peg to the
// end(final) peg by using the helper peg
MoveRings(b, e);// to move the last ring to the end(final) peg
count++; // increment the number of steps before displaying
cout << "There has been " << count << " moves. "<< endl;
Pegs(D - 1, b, e, h);
// to move N-1 rings from the helper peg to the end(final) peg with the help of
// first peg
//Display ( D(rings), First Peg, End(Final) Peg, Helper Peg );
}
}
One problem that I can see immediately is that your header file defines StackType to prevent double inclusion, which is also used as a class name. After #define StackType, it ends up being a macro that expands to nothing, so your code looks like class { ... }.
You should use a symbol to prevent double inclusion that isn't used for anything else. The typical thing to use is STACKTYPE_H for a file called StackType.h.
Once you've fixed this, some other problems you're experiencing might go away. Please come back with an update if you're having more problems, and post the exact compiler errors if you do.

Resources