Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
New Developer
Posts: 104
Registered: ‎09-25-2013
My Device: BB 10
My Carrier: BB 10

getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

Hi All,

In my BB 10 native app, I am dealing with the huge data. app is running at some point of time I am getting " Malloc Check Failed: :../../dlist.c:1309 " and crashing the BB 10 app

what is this error , when we get this and how to fix it?

Please Help,
Thanks !!!

Developer
Posts: 6,152
Registered: ‎07-05-2012
My Device: Playbook, Dev Alpha C, Z10 LE, Z30
My Carrier: Orange

Re: getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

[ Edited ]

malloc is the C++ way of allocating memory blocks.

 

Whether it is used directly or indirectly a check should be made on whether the allocation is successful.

 

If you are using it directly then check the returned pointer is non-null, if you are using it indirectly then check if the function you used has a return error or exception and deal with that.

 

If you are using it through a library then check if there are any build flags or preprocessor defines that need to be set.

 


If you've been helped click on Like Button, if you've been saved buy the app. Smiley Happy

Developer of stokLocker, Sympatico and Super Sentences.
New Developer
Posts: 104
Registered: ‎09-25-2013
My Device: BB 10
My Carrier: BB 10

Re: getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

[ Edited ]

Here I am posting some code...can you please tell me where I am wrong.

/*
 * Client.h
 *
 *  Created on: Dec 24, 2013
 *      Author: user
 */

#ifndef CLIENT_H_
#define CLIENT_H_

/*
 * Client.cpp
 *
 *  Created on: Dec 23, 2013
 *      Author: user
 */

#include <QtNetwork/qtcpsocket.h>
#include <unistd.h>
#include <stdlib.h>
#include <qtextstream.h>
#include <QObject>
#include <QTimer.h>
#include "applicationui.hpp"

#include <bb/system/SystemToast>
#include <bb/system/SystemUiPosition>
#include <bb/system/SystemListDialog>

unsigned int delay(unsigned int duration);
using namespace bb::system;
class Client: public QObject
{
Q_OBJECT
public:
ApplicationUI *app;
		Client()
	 	{
			s_instance= this;
	 		//reconnect(host,port);
	 	}
		 static Client *s_instance;
	virtual ~Client()
	{
	}
	void worker();
	void reconnect(const QString &host, const ushort port);

	 static Client& instance();

	 void setIp(const QString &host1,const ushort port1,ApplicationUI *_app){
		 host=host1;
		 port=port1;
		 app=_app;
		 reconnect(host1,port1);
	 }
	 bool isNetworkAvailable();
	 void  HttpPost(QString URL);

public slots:

	void closeConnection();
	void socketConnected();

	void socketConnectionClosed();

	void sendToServer();

	void socketClosed();

	void reqSymbols(QString req);

	void socketReadyRead();

	void socketError(QAbstractSocket::SocketError socketError);



private slots:
	 void   HttpResponse(QNetworkReply* reply);

private:
	QTcpSocket *socket;
	QString remaining;
	 QString host;
	 ushort port;

};

#endif /* CLIENT_H_ */

 

/*
 * Client.cpp
 *
 *  Created on: Dec 23, 2013
 *      Author: user
 */

#include <QtNetwork/qtcpsocket.h>

#include <qtextstream.h>
#include <qtconcurrentrun.h>
#include<Client.h>
#include<QtCore/QStringList>
#include "Helper.h"
#include <bb/data/JsonDataAccess>
#include "DatabaseOperations.h"
#include <unistd.h>
#include <stdlib.h>
#include <QtNetwork/qnetworkconfiguration.h>
#include <QtCore/QList>

#include "ClientReq.h"
#include "DatabaseOperations.h"
#include <bb/data/JsonDataAccess>
#include <QByteArray>
#include "Helper.h"
#include <QThread>
#include <QtNetwork/qnetworkconfiguration.h>
#include <bb/device/HardwareInfo.hpp>
#include "SubcriptDB.h"

#include "SocketBase.h"
#include "Helper.h"
#include "AlertsList.h"
#include <bb/cascades/Application>
#include <QtNetwork/qtcpsocket.h>
#include <QtCore/qthread.h>
#include <QtCore/qdebug.h>
#include <bb/cascades/JavaScriptWorld>
#include <bb/cascades/Label>
#include <QtCore/QList>
#include <unistd.h>
#include <stdlib.h>
#include<QList>
#include <QByteArray>
#include <bb/data/JsonDataAccess>
#include <unistd.h>
#include "DatabaseOperations.h"
#include "applicationui.hpp"
#include <QtNetwork/qnetworkconfiguration.h>
#include <bb/device/HardwareInfo.hpp>

#include <bb/system/SystemToast>
#include <bb/system/SystemUiPosition>
#include <bb/system/SystemListDialog>
#include <QObject>
#include <QtSql/QtSql>
#include <QDebug>
#include <QLocale>

QString reqType;
using namespace bb::cascades;
using namespace bb::data;
//using namespace bb::system;
using namespace bb::device;

unsigned int delay(unsigned int duration);
int isReconnect = -1;
bool isReconnected = false;
SystemDialog * dialogExit22;
bool IsDonePre;
int Con_Count = 0;
bool isReading = false;
Client* Client::s_instance = 0;
bool noInternet=false,gotRes=false;
bool isDone = false;
bool isDone1 = false;
QString Helper;
QByteArray data("");
int counter = 1;
//QNetworkAccessManager *mNetworkAccessManager;
void Client::reconnect(const QString &host, const ushort port) {


	socket = new QTcpSocket(this);

	connect(socket, SIGNAL(connected()), SLOT(socketConnected()));
	connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead()));
	connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this,
			SLOT(socketError(QAbstractSocket::SocketError)));


	socket->connectToHost(host, port);

	if (socket->waitForConnected(1000)) {
		printf("\n ***********waitForConnected*********Connected");
	}

	if (socket->state() == QAbstractSocket::ConnectedState){
		printf("\n ***********socket state*********Connected");
		isReconnect = 1;
	}
	else{
		printf("\n ***********socket state*********Not connected");
	}

}

void Client::socketConnected() {

	qDebug() << "\n &^&^&^&^&^&^&^&^&^&^&^  socketConnected";
	QString dev_id = Helper::device_pin;
	QString type = Helper::userType;

	QString conData = "Login:" + dev_id + "," + dev_id + "," + dev_id + ","
			+ type + ",blackberry";

	qDebug() << "777777777777" << conData;
	int returnval = socket->write(conData.toUtf8());
	if (!socket->waitForBytesWritten()) {

		printf("writeLine: the write to the socket failed\n");
	} else {
		qDebug() << " \n Connection Data Client::sendToServer" << conData<< "            " << returnval;
	}

}

void Client::reqSymbols(QString req) {

	Helper::clearSymbolsList(); // clear the previos request stack
	Helper::tailrequest = req;
	int bytesAvail = -1;
	reqType = req;
	qDebug() << "\n ####################################  reqSymbols  " + req;
	int returnval = socket->write(req.toUtf8());
	if (!socket->waitForBytesWritten()) {

		printf("\n reqSymbols: the write to the socket failed\n");
	} else {
		qDebug() << " \n reqSymbols " << "            " << returnval;

	}
}




void Client::worker() {

	if (IsDonePre && !isReading && socket->state() == QAbstractSocket::ConnectedState) {
		if (Helper::reqText != "") {
			qDebug()<< "\n !!!!!!!!!!!!!!!!!!!!!  req from worker method !!!!!!!!!!!!!!!!!!!!!!!";
			reqSymbols(Helper::reqText);
			//Helper::tailrequest = Helper::reqText;
			Helper::reqText = "";
		}
	}
}




void Client::socketReadyRead() {

	//qDebug() << "\n init socketReadyRead called";
	int bytesAvail = -1;

	isReading = true;

	bytesAvail = socket->bytesAvailable();

	data.append(socket->readAll());

	isReading = false;
	QString resData = QString(data);
	data.clear();
	int currentTime = QDateTime::currentMSecsSinceEpoch() / 1000;
	//qDebug() << " \n ****" << " " << currentTime << "  " << resData;

	//******** for Only Fresh Login **********
	if(resData == "LoginStatus:1"){
		qDebug()<<"<<<<<<<<<<<<<<<<<<<<<<< Log in Ok  >>>>>>>>>>>";
		resData="";
		data.clear(); // clear other wise Added to  Helper::requestAll

		if(!Helper::isReq_All){
			qDebug()<<"<<<<<<<<<<<<<<<<<<<<<<< sending RequestSymbols:All >>>>>>>>>>>";
			Helper::requestAll = "";
			reqSymbols("RequestSymbols:All");
		}
		Helper::isLogin = true;
		return;
	}
	// ******** for Only Request All **********
	if (reqType == "RequestSymbols:All" ) {
		//if(!resData.endsWith(']'))
		qDebug()<<"reading request all >>>>>>>>>>>";
		Helper::requestAll += resData;
		//qDebug() << "\n Helper::requestAll"<<Helper::requestAll;
		if(resData.endsWith(']')){
			qDebug()<<"<<<<<<<<<<<<<<<<<<<<<<< Finished reading request all >>>>>>>>>>>";
			reqSymbols(Helper::reqText);

			Helper::reqText="";
			Helper::isReq_All=true;
			IsDonePre = true;
		}
		return;
	}

	// For Reading
	if (resData.length() > 0 ) {
		//QString line="";
		bool skipremaining = false;
		QString ba;
		if(resData.startsWith("{")){
			ba = resData;
		}else{
			ba = remaining +resData;
		}
		//data.clear();
		QStringList testList = ba.split('}');
		JsonDataAccess jda;
		for (int i = 0; i < testList.size(); i++) {
		//	qDebug() << "\n Socket read this:: \n   " << i << testList.at(i);
			if (testList.at(i) != "") {
				//qDebug() << "\n Socket read this:: \n   " << i << testList.at(i);
				QString temp;

				if (testList.at(i) != "]" && testList.at(i) !="LoginStatus:1") { // somes times (quick watch recoonect) "LoginStatus" adding to temp
					temp = "[" + testList.at(i) + "}]";
					//				  qDebug()<<i;

				}


				//qDebug()<<"\n Socket read this:: \n "<< temp;
				QVariantList data = jda.loadFromBuffer(temp).toList();

				//qDebug()<<"data size:::::"<<data.size();
				if (!jda.hasError()) {
					Helper::dataString += testList.at(i) + "},";

					Helper::counter++;

				} else {
					//qDebug()<<"\n json error socketReadyRead \n \n  ";
					// qDebug() << testList.at(i);
					if (testList.at(i).contains("AlertStatus")) {
						bool isBool;

						QString str = testList.at(i);
						qDebug() << str.split("AlertStatus:");
						QString temp = testList.at(i).split("AlertStatus:").at(1);
						QString temp1 = temp.split(';').at(0);
						QString temp2 = temp1.split(',').at(0);
						QString temp3 = temp1.split(',').at(1);

						int serverid = temp2.toInt(&isBool); // EURUSD is reached : 1.444564
				        DatabaseOperations::updateAlertServerId(temp3,serverid);

						//app->alertShow(serverid);

						skipremaining = true;
					}
					if (testList.at(i).contains("AlertExecuted")) {
						bool isBool;
						QString str = testList.at(i);
						QString temp =
								testList.at(i).split("AlertExecuted:").at(1);
						QString temp1 = temp.split(';').at(0);
						int serverid = temp1.toInt(&isBool);
						app->alertShow(serverid);
						skipremaining = true;
					}

					if (!skipremaining && i + 1 == testList.size()) {
						remaining = testList.at(i);
					}
				}
			}
		}
	}



	// this is for Frequent request update and drop update
	if (Helper::reqText != "") {
		qDebug()<<"\n **************this is for Frequent request update and drop update";
	//	Helper::tailrequest = Helper::reqText;
		reqSymbols(Helper::reqText);
		Helper::reqText = "";
	}
  // For Only after Reconnected
	if (isReconnect == 1 ) {
		qDebug()<<"\n **************request when reconnected";
		isReconnect = -1;
		if (Helper::reqText == ""){
			reqSymbols(Helper::tailrequest);
		}
		else
		{
			reqSymbols(Helper::reqText);
			Helper::reqText = "";
		}
	}

}










void Client::HttpPost(QString URL ){
	QNetworkRequest request = QNetworkRequest();
	request.setUrl(QUrl(URL));
	QNetworkAccessManager *mNetworkAccessManager = new QNetworkAccessManager(this);

	bool result=connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply*)),
			this, SLOT(HttpResponse(QNetworkReply *)));

	//qDebug() << result;
	mNetworkAccessManager->get(request);
	//printf("::: Request made to Service :::");
	qDebug() << "::: Client.cpp  Request made to Service :::";

}

void Client::HttpResponse(QNetworkReply* reply) {


	if (reply->error() == QNetworkReply::NoError) {
		gotRes=true;
		qDebug() << "\n &^&^&^&^&^&^&^&^&^&^&^  socketError";
			 if (isReconnect == -1 || isReconnect == 1) {
				delay(5000);
				isReconnect = 0;
				qDebug() << "Trying to reconnect"; //   192.168.1.100
				reconnect("83.101.141.1", 9088);
				//isReconnected=true;

			}
	} else {
		//qDebug() << "\nData from yahoo ::: Problem with the network";
		qDebug() << "\n No Internet **********" << reply->errorString();
		//showDialog(-1000);
		app->alert("please try again, if failed again restart the application");
		QCoreApplication::processEvents();
		gotRes=true;
		noInternet=true;
	}
}












void Client::socketConnectionClosed() {
	qDebug() << "\n &^&^&^&^&^&^&^&^&^&^&^  socketConnectionClosed";
}

void Client::socketClosed() {
	qDebug() << "\n &^&^&^&^&^&^&^&^&^&^&^  socketClosed";
}

void Client::socketError(QAbstractSocket::SocketError socketError) {

	HttpPost("https://www.google.co.in/");
}
void Client::closeConnection() {
	socket->close();
	if (socket->state() != QAbstractSocket::ConnectedState) {
		// We have a delayed close.
		connect(socket, SIGNAL(delayedCloseFinished()), SLOT(socketClosed()));
	} else {
		// The socket is closed.
		socketClosed();
	}
}

void Client::sendToServer() {

}
Client& Client::instance() {
	if (!s_instance)
		s_instance = new Client();
	return *s_instance;
}
bool Client::isNetworkAvailable() {
	bool isFound = false;
	QNetworkConfigurationManager netMgr;
	QList<QNetworkConfiguration> mNetList = netMgr.allConfigurations(
			QNetworkConfiguration::Active);

	if (mNetList.count() > 0) {

		if (netMgr.isOnline()) {
			isFound = true;
		}
	}
	qDebug() << "\n ************** isNetworkAvailable:::" << isFound;
	return isFound;
}

 

/*
 * MyThread.h
 *
 *  Created on: Dec 24, 2013
 *      Author: satishb
 */

#ifndef MYTHREAD_H_
#define MYTHREAD_H_

#include <qthread.h>
#include<Client.h>

class MyThread: public QThread
{
	 Q_OBJECT

public:
	MyThread();
	virtual ~MyThread();
	void startMyThread();
protected:
    void run();

};


#endif /* MYTHREAD_H_ */

 

/*
 * MyThread.cpp
 *
 *  Created on: Dec 24, 2013
 *      Author: satishb
 */

#include "MyThread.h"


MyThread::MyThread()
{
	// TODO Auto-generated constructor stub

}

MyThread::~MyThread()
{
	// TODO Auto-generated destructor stub
}
void MyThread::startMyThread(){

	start();
}
void MyThread::run()
 {

     while(true){
    	Client::s_instance->worker();
    	 sleep(1);
     }
 }

 in my main..cpp 

Application app(argc, argv);
	Client *client = new Client();

		    QThread *thread = new QThread(&app);
		        thread->start();
		        client->moveToThread(thread);
		        MyThread th;
		        th.startMyThread();

 and in my ApplicationUI.cpp

 

 Client::s_instance->setIp(IP,XXXX,this );

 Please Help,

 

 Thanks!!!

Developer
Posts: 1,163
Registered: ‎03-20-2013
My Device: Red LE Developer Z10
My Carrier: Fido

Re: getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

Unfortunately, sometimes you can't check malloc success yourself since it is buried in Cascades or Qt class you are using. Yesterday I was experimenting with some QAccelerometer code, and was getting a malloc failure every time I tried to start the sensor. Turned out I was neglecting to connect the sensor to a backend before calling start(). The malloc failure was coming from inside QSensor, something you can't check directly, I was only able to figure out my error by scouring the Web for sample code to see how others were successfully using QAccelerometer.


BBSJdev wrote:

malloc is the C++ way of allocating memory blocks.

 

Whether it is used directly or indirectly a check should be made on whether the allocation is successful.

 

If you are using it directly then check the returned pointer is non-null, if you are using it indirectly then check if the function you used has a return error or exception and deal with that.

 

If you are using it through a library then check if there are any build flags or preprocessor defines that need to be set.

 






Developer of Built for BlackBerry certified multiFEED RSS/Atom feed reader and aggregator.  multiFEED Icon

Play nice: Clicking Like Button on posts that helped you not only encourages others to continue sharing their experience, but also improves your own rating on this board. Also, don't forget to accept a post if it solves your problem or answers your question.
Developer
Posts: 526
Registered: ‎05-17-2009
My Device: 9900
My Carrier: ATT

Re: getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

In my experience, you usually get this when QML or a listview or some cascades component is trying to use a QObject that has already been deleted.

Like all of my posts
New Developer
Posts: 104
Registered: ‎09-25-2013
My Device: BB 10
My Carrier: BB 10

Re: getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

[ Edited ]

then how to tell the qml components not to use QObject  that already deleted ?

Developer
Posts: 1,524
Registered: ‎12-18-2012
My Device: Z30, Z10 LE, DevAlpha C, PlayBook

Re: getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

Hi,

 

@BBSJdev, from my tests on desktop (Linux & Windows), malloc and operator new[] will successfully allocate more memory than available. But the app will crash when this memory is actually filled with data. It SHOULD return NULL or throw an exception where there's no memory available, but in practice malloc returns NULL only in rare cases, for example when the size of swap file is changed in system settings (half of the running programs crash when doing this). Smiley Very Happy

 

Most likely the behaviour is similar on QNX. It's a good practice to check return values when allocating memory, but most likely this is not causing the crash in this code.

 

@

I think crash happens because of memory leaks. The system eventually runs out of memory. Might be threading issues as well.

 

From the brief look at the code I see these problems (there may be more):

 

1) Memory leak:

 

socket = new QTcpSocket(this);

A new socket is created on every call to reconnect. Where is it destroyed? It's parented to Client, but if Client is not destroyed, QTcpSockets will continue to exist and accumulate on each call to this function.

 

2) Do you really need to use blocking APIs of QTcpSocket with waitForConnected, sleep() etc? Mixing it with signals  complicates application logic a lot. Imho it's easier to implement a finite state machine (FSM) and use QTcpSocket's async notifications. Pauses (on reconnect) can be implemented using QTimer. This won't require starting another thread unless you're doing some heavy processing on received data.

 

If using blocking API-s, it's easier to spawn a thread per connection, but it's better not to mix them with async notifications.

 

3) run() method is reimplemented, but Qt event loop isn't started. Without an event loop, some Qt classes won't function properly:

 

void MyThread::run()
 {

     while(true){
    	Client::s_instance->worker();
    	 sleep(1);
     }
 }

I recommend checking this article on threads, it contains some essential info:

http://blog.debao.me/2013/08/how-to-use-qthread-in-the-right-way-part-1/

http://blog.debao.me/2013/08/how-to-use-qthread-in-the-right-way-part-2/

 

4)

void Client::HttpResponse(QNetworkReply* reply) {

reply isn't destroyed anywhere. Is should be deleted using reply->deleteLater();

But deleteLater()  won't work properly because Qt event loop wasn't started in reimplemented version of run().

 

5) In one function there's a call to

		QCoreApplication::processEvents();

 

processEvents() is a hack and shouldn't be needed if event loop is working properly. It's needed only for processing events in a blocking loop to update UI, but this can be solved in different way.

 

6)

void Client::HttpPost(QString URL ){
	QNetworkRequest request = QNetworkRequest();
	request.setUrl(QUrl(URL));
	QNetworkAccessManager *mNetworkAccessManager = new QNetworkAccessManager(this);

New QNetworkAccessManager instance is created for every request and isn't destroyed anywhere.

It's better to create a single QNetworkAccessManager instance and reuse it for different requests.

 

7) I assume methods such as HttpPost() are called from main thread without any thread synchronization?

They should be called via signal/slot mechanism using QueuedConnection call type, but this won't work without an working event loop. Using mutexes for synchronization is another option. Do not call them directly, this will lead to unpredictable behavior.

 


Andrey Fidrya, @zmeyc on twitter
Developer
Posts: 6,152
Registered: ‎07-05-2012
My Device: Playbook, Dev Alpha C, Z10 LE, Z30
My Carrier: Orange

Re: getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

[ Edited ]

Ooh I feel like I'm being attacked. Smiley Happy

 

@greenmr My second line was poorly worded but the third line should have made it clear that you should look to see, from a documentation point of view, if an error is returned not that there will always be one.

 

@Zmey I did say 'non-null' so it was worded correctly, a null pointer indicating no memory has been allocated.

 

And I agree with you Zmey something is taking too much memory and eventually running out.

 

I knew what I meant even if you guys didn't. Smiley Wink

 

[Edit] Rereading this yes it wasn't the finest reponse I've ever given but I was preparing to receive guests and in a hurry. Luckily your two verbose responses are sure to have put sharath to sleep helped sharath out. Smiley LOL

 

 

 


If you've been helped click on Like Button, if you've been saved buy the app. Smiley Happy

Developer of stokLocker, Sympatico and Super Sentences.
Developer
Posts: 6,152
Registered: ‎07-05-2012
My Device: Playbook, Dev Alpha C, Z10 LE, Z30
My Carrier: Orange

Re: getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

I also realise I've misread Zmey's response, I thought his line containing 'SHOULD' was a complaint about my wording I now realise Zmey meant it as a complaint against the implementation of malloc. Which I also agree with.

 

I'll shut up now. Smiley Happy

 

 


If you've been helped click on Like Button, if you've been saved buy the app. Smiley Happy

Developer of stokLocker, Sympatico and Super Sentences.
Developer
Posts: 1,163
Registered: ‎03-20-2013
My Device: Red LE Developer Z10
My Carrier: Fido

Re: getting this “ Malloc Check Failed: :../../dlist.c:1309 ” and crashing the BB 10 app

No attack intended from me... can't speak for others though.

 

Smiley Wink


BBSJdev wrote:

Ooh I feel like I'm being attacked. Smiley Happy

 

@greenmr My second line was poorly worded but the third line should have made it clear that you should look to see, from a documentation point of view, if an error is returned not that there will always be one.

 

@Zmey I did say 'non-null' so it was worded correctly, a null pointer indicating no memory has been allocated.

 

And I agree with you Zmey something is taking too much memory and eventually running out.

 

I knew what I meant even if you guys didn't. Smiley Wink

 

[Edit] Rereading this yes it wasn't the finest reponse I've ever given but I was preparing to receive guests and in a hurry. Luckily your two verbose responses are sure to have put sharath to sleep helped sharath out. Smiley LOL

 

 

 






Developer of Built for BlackBerry certified multiFEED RSS/Atom feed reader and aggregator.  multiFEED Icon

Play nice: Clicking Like Button on posts that helped you not only encourages others to continue sharing their experience, but also improves your own rating on this board. Also, don't forget to accept a post if it solves your problem or answers your question.