Crash reading json file from server

Hi All,
I have a code on OF that reads JSON packages from a server. It is signals from EEG sensor.
My issue is that the app is very unstable, crashes on different moments, but I don’t find where exactly.
Any suggestion?
Thanks for the help
David

Here the code.

#pragma once
#include "ofMain.h"
#include "ofxJSON.h"
#include "ofxNetwork.h"
#include "ofxOsc.h"

#define HOST "localhost"
#define PORT 8500

// listen on port 12345
#define PORTLISTEN 8510

class ofApp : public ofBaseApp
{
public:
	void setup();
	void update();
	void draw();
	void sendCommand(string command);
	void sendRecord(string command, float inTime);
	void keyPressed(int key);
	vector<ofxJSONElement> receiveMessage();
	void fitEegData(ofxJSONElement element, float * data);
	void fitEegAlpha(ofxJSONElement element, float * data);
	void fitEdaData(ofxJSONElement element, float * data);
	void fitResultData(ofxJSONElement element, float * data);
	void exit();
		
	ofxTCPClient client;
	
	ofxJSONElement json;

	ofxOscSender sender;
	ofxOscReceiver receiver;
	
	bool started;	
	string errorDetected;

	float * ecgSignal;
	float * edaTonic;
	float * result;
	float * eegAlpha;
	float * impact;
	int away;

	ofBuffer log;
	char* buffer;
	int writeIndex;

	bool sendData = false;

	float ecg;
	float timestamp;
};

The other file:


#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
//	ofSetFrameRate(30);
	client.setup("127.0.0.1", 5000);
	if (client.isConnected()) cout << "connected to server" << endl;
	else cout << "connection failed" << endl;
	
	// open an outgoing connection to HOST:PORT
	sender.setup(HOST, PORT);
	receiver.setup(PORTLISTEN);

	errorDetected = "non";
	started = false;

	ecgSignal = new float[8];
	for (int i = 0; i < 8; i++) ecgSignal[i] = 0;
	edaTonic = new float[8];
	for (int i = 0; i < 8; i++) edaTonic[i] = 0;
	result = new float[10];
	for (int i = 0; i < 10; i++) result[i] = 0;
	eegAlpha= new float[4];
	for (int i = 0; i < 4; i++) eegAlpha[i] = 0;
	impact = new float[3];
	for (int i = 0; i < 3; i++) impact[i] = 0;

	ecg = 0;

	log = * (new ofBuffer());

	buffer = new char[2048];
	for (int i = 0; i < 2048; i++) {
		buffer[i] = '.';
	}

	writeIndex = 0;
}

//--------------------------------------------------------------
void ofApp::update(){
	if (client.isConnected() && started) {
		vector<ofxJSONElement> elements = receiveMessage();
		away = 0;
		for (int i = 0; i < elements.size(); i++) {
			ofxJSONElement element = *new ofxJSONElement();
			element = elements[i];
			//if data frame
			for (Json::ArrayIndex i = 0; i < element["DATA"].size(); i++) {
			
				//get element at index i
				ofxJSONElement sub = elements[i]["DATA"][i];
				//display value type and timestamp
				//store eeg values	
				timestamp = sub["Timestamp"].asFloat();
				//timestamp = sub["Timestamp"][0].asFloat();
				if (sub["ID"].asString() == "ecg_signal") fitEdaData(sub, ecgSignal);
				if (sub["ID"].asString() == "eda_fasic") fitEdaData(sub, edaTonic);
				if (sub["ID"].asString() == "eeg_alpha") fitEegAlpha(sub, eegAlpha);
				if (sub["ID"].asString() == "impact") fitEegData(sub, impact);
				if (sub["ID"].asString() == "result") fitResultData(sub, result);

				//store ecg values
				if (sub["ID"].asString() == "ecg_hr") ecg = sub["Values"][0].asFloat();
				if (sub["ID"].asString() == "away") away = 1;	
			}
			ofxOscMessage connect;
			connect.setAddress("/error");
			if (element["STATUS"].asString() == "OK") {
			//	cout << "start request accepted." << endl;
				errorDetected = "ok";
				ofLogError(element["MSG"].asString());
			}
			else if (element["STATUS"].asString() == "Error") {
				//error in the server when receiving the message
				errorDetected = "error";
				ofLogError(element["MSG"].asString());
			}
			connect.addStringArg(errorDetected);
			sender.sendMessage(connect, false);
		} 
	}
	// check for waiting messages
	while (receiver.hasWaitingMessages()) {
		// get the next message
		ofxOscMessage m;
		receiver.getNextMessage(m);
		// check for mouse moved message
		if (m.getAddress() == "/start") {
			sendCommand("start");
			started = true;
		} 
		else if(m.getAddress() == "/stop"){
			sendCommand("stop");
			started = false;
		}
		else if (m.getAddress() == "/start_clip") {
			sendRecord("start_clip", timestamp);
		}
		else if (m.getAddress() == "/stop_clip") {
			sendRecord("stop_clip", timestamp);
		}
	}
	//sending data
	if (client.isConnected() && started) {
		//sender.enableBroadcast();
		ofxOscMessage ecgMessage;
		ecgMessage.setAddress("/ecg");
		ecgMessage.addFloatArg(ecg);
		sender.sendMessage(ecgMessage, false);
		

		for (int i = 0; i < 4; i++) {
			ofxOscMessage alpha;
			alpha.setAddress("/alpha");
			alpha.addInt32Arg(i);
			alpha.addFloatArg(eegAlpha[i]);
			sender.sendMessage(alpha, false);
		}

		for (int i = 0; i < 3; i++) {
			ofxOscMessage imp;
			imp.setAddress("/impact");
			imp.addInt32Arg(i);
			imp.addFloatArg(impact[i]);
			sender.sendMessage(imp, false);
		}

		//draw ecg Signal
		for (int j = 0; j < 8; j++) {
			ofxOscMessage m;
			m.setAddress("/ecgSignal");
			m.addInt32Arg(j);
			m.addFloatArg(ecgSignal[j]);
			sender.sendMessage(m, false);
		}

		//draw result
		for (int j = 0; j < 10; j++) {
			ofxOscMessage m;
			m.setAddress("/result");
			m.addInt32Arg(j);
			m.addFloatArg(result[j]);
			sender.sendMessage(m, false);
		}

		//draw eda tonic
		for (int j = 0; j < 8; j++) {
			ofxOscMessage m;
			m.setAddress("/tonic");
			m.addInt32Arg(j);
			m.addFloatArg(edaTonic[j]);
			sender.sendMessage(m, false);
		}
		ofxOscMessage hands;
		hands.setAddress("/away");
		hands.addInt32Arg(0);
		hands.addInt32Arg(away);
		sender.sendMessage(hands, false);
		//sender.disableBroadcast();
	}
}
//--------------------------------------------------------------
vector<ofxJSONElement> ofApp::receiveMessage() {
	vector<ofxJSONElement> ret;
	int startIndex = 0;
	int readIndex = 0;	
	//write received bytes after last written thing
	int writtenBytes = client.receiveRawBytes(buffer + (writeIndex)* sizeof(char), 700);
	if (writtenBytes > 0) {
		//look for valid JSON strings in buffer and store them in vector
		while (readIndex <= writeIndex + writtenBytes) {
			string s(buffer);
			string p(s.begin() + startIndex, s.begin() + readIndex);
			ofxJSONElement element = *new ofxJSONElement();
			if (element.parse(p)) {
				ret.push_back(element);
				startIndex = readIndex;
				//if (sendData) {
				//	log.append("C ");
				//	log.append(p);
				//	log.append("\n");
				//}
			}
			readIndex++;
		}

		//move remainings to begining of buffer
		for (int i = 0; i < (writtenBytes + writeIndex - startIndex); i++) buffer[i] = buffer[i + startIndex];
		//set index at which to write next time
		writeIndex += writtenBytes - startIndex;

		//clear the rest of the buffer
		for (int i = writeIndex; i < 2048; i++) buffer[i] = '.';
	}
	return ret;
}
//--------------------------------------------------------------
void ofApp::fitEegData(ofxJSONElement e, float * m) {
		for (int i = 0; i < 3; i++) {
			m[i] = e["Values"][i].asFloat();
		}		
}
//--------------------------------------------------------------
void ofApp::fitEegAlpha(ofxJSONElement e, float * m) {
	for (int i = 0; i < 4; i++) {
		m[i] = e["Values"][i].asFloat();
	}
}
//--------------------------------------------------------------
void ofApp::fitEdaData(ofxJSONElement e, float * d) {
	for (int i = 0; i < 8; i++) {
		d[i] = e["Values"][i].asFloat();
	}
}
//--------------------------------------------------------------
void ofApp::fitResultData(ofxJSONElement e, float * d) {
	for (int i = 0; i < 10; i++) {
		d[i] = e["Values"][i].asFloat();
	}
}

//--------------------------------------------------------------
void ofApp::draw() {
	ofBackground(0);	
}
//--------------------------------------------------------------
void ofApp::sendRecord(string command, float inTime) {
	if (client.isConnected()) {
		//send command to server
		//{ "DATA":[{"ID":"stop_clip","Timestamp" : 0,"Values" : []}] }
		string s = "{ \"DATA\":[{\"ID\":\""+command+"\",\"Timestamp\" : "+to_string(inTime)+",\"Values\" : []}] }";
		client.sendRaw(s);										
	}
}
//--------------------------------------------------------------
void ofApp::sendCommand(string command) {
	if (client.isConnected()) {
		//send command to server
		string s = "{ \"COMMAND\": \"" + command + "\" }";
		client.sendRaw(s);
	}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key) {
	if (key == OF_KEY_UP) {
		sendCommand("start");
		started = true;
	}
	if (key == OF_KEY_DOWN) {
		sendCommand("stop");
		ofBufferToFile("log.txt", log);
	}
	if (key == OF_KEY_LEFT) sendRecord("stop_clip", timestamp);
	if (key == OF_KEY_RIGHT) sendRecord("start_clip", timestamp);
}
//--------------------------------------------------------------
void ofApp::exit() {
	ofBufferToFile("log.txt", log);
	sendCommand("stop");
}

Quick checking your code, i’ve seen some issues that may cause the instability.

You heavily use the “new” operator in your code, most places unnecessary.

For example:

ofApp.h: float * ecgSignal
ofApp.cpp: ecgSignal = new float[8];

could be changed to

float ecgSignal[8];

which avoids having to manually delete the object.

Also:

ofApp.h: ofBuffer log;
ofApp.cpp: log = * (new ofBuffer());

must be changed to

ofApp.h: ofBuffer log;
ofApp.cpp: nothing

Declaring the ofBuffer log in the .h already creates an ofBuffer object, there is no need to construct it again in the .cpp. When calling the “new” operator you are creating a new object, and if you apply the * you dereference the pointer that the new operator generated for the new object, and if you apply “log =” then you are copying the object, so the newly created object is leaked.

Fix those issues and check for stability.

Also, can you try to find the specific cause of the issue? Find the line where it crashes

thanks for your answer. In deed this code looks more like java. This “new” method were exactly the problem.