Arduino, losing value of variable during code execution - c++

I'm encountering a strange problem on an arduino sketch.
I'ts a sketch quite complex so i've decided to write in whith classes.
Basically it recieve some data via TCP connection in JSON format and do some operations according form the decoded data.
I decode the received JSON inside the CLASS "PacketManager", using the library "Arduino Json". Then i pass the JSON object to the class "Bollard" for the execution of the commands (the code will follow). The strange thing is that on the "Bollard" Class in the method "CommandExecutor" I access to the data I passed and I can use them but at some point during the code of the same method that data go to 0.
Ofcourse i've checked that the the data is not overwriten in the method. The sketch does not have any interrupt or multythread. Seems like the variable get de-allocated form memory or the memory block get overwriten.
/// FRAGMENT OF CLASS PACKETMANAGER THAT RECEIVE THE JSON
void PacketManager::readPacket(){
resultRead reads=socket.readSocket(); //get data from soket
if(reads.mainCounter>0){ // if data
delay(150);
StaticJsonBuffer<200> jsonBuffer; //create a static json buffer form the library ArduinoJson.h
JsonObject& incomingFrame = jsonBuffer.parseObject((char*)reads.frame); //craete a JSON oblect
delay(150);
incomingFrame.printTo(Serial); // print the Incoming JSON
Serial.println();
if(incomingFrame.success()){ // check if JSON get decoded correclty
Serial.println("JSON DECODED SUCCESSFULLY");
unsigned int eventType=incomingFrame["eventType"];
unsigned int packetNumber=incomingFrame["packetNumber"];
if(eventType==ACK_STANDARD_MESSAGE){ // ACK standard case
if(this->checkACK(packetNumber)){ // CHECK If the incoming ACK found a corrispondence with the packet sended
#ifdef DEBUG_MODE
Serial.println("ACK RECEIVED");
#endif
bollard.commandExecute(incomingFrame); // if ack is in response of a sended command execute a command form the class bollard.
}
}
................ CODE CONTINUE. THE ERROR IS ON METHOD bollard.commandExecute(incomingFrame)
/////////////// FRAGMENT OF CLASS BOLLARD THAT USE THE JSON OBJECT
commandResult* BikeBollard::commandExecute(JsonObject& incomingFrame){
unsigned int* statusResponse= new unsigned int; // CREATE STATIC POINTER
unsigned int* eventType= new unsigned int;
unsigned int* commandType= new unsigned int;
unsigned int* packetNumber= new unsigned int;
// GET DATA FORM THE JSON OBJECT
unsigned int statusResponse_volatile=(unsigned int)incomingFrame["status"];
unsigned int eventType_volatile=(unsigned int)incomingFrame["eventType"];
unsigned int commandType_volatile=(unsigned int)incomingFrame["commandType"];
unsigned int packetNumber_volatile=(unsigned int)incomingFrame["packetNumber"];
// ASSIGN TO THE STATIC POINTED VALUE
*statusResponse=statusResponse_volatile;
*eventType=eventType_volatile;
*commandType=commandType_volatile;
*packetNumber=packetNumber_volatile;
commandResult* result;
Serial.print("STATUS OF THE RESPONSE ");Serial.println(*statusResponse); // correct value
Serial.print("EVENT TYPE ");Serial.println(*eventType); // correct value
Serial.print("COMMAND TYPE ");Serial.println(*commandType); // correct value
Serial.print("PACKET NUMBER ");Serial.println(*packetNumber); // correct value
///////////////////////////// FROM HERE SOMETIMES THE VALUES *commandType AND *eventType GO TO 0 WITHOUT A REASON ///////////////////////////
if(*eventType==ACK_STANDARD_MESSAGE){ // ACK vase
Serial.print("STATUS OF THE RESPONSE ");Serial.println(*statusResponse); // correct value
*eventType=*commandType;
Serial.print("STATUS OF THE RESPONSE ");Serial.println(*statusResponse); // correct value
result->ackPriority=false;
}
result->type=*eventType;
#ifdef DEBUG_MODE
Serial.print("BOLLARD: EXECUTE COMMAND "); Serial.println(*eventType);
#endif
switch(*eventType){ // wrong value pass form the correct value to 0 sometimes
case MSG_UP:
{
Serial.println("ACK MSG_UP Received");
result=this->executeMessageUp(*eventType, *packetNumber);
break;
}
case MSG_LATCH:
{
Serial.println("ACK MSG_LATCH Received");
this->executeMessageLatch(*eventType, *packetNumber);
break;
}
case MSG_UP_OK:
{
// DO SOMETHING
break;
}
case MSG_UP_ERROR:
{
// DO SOMETHING
break;
}
case MSG_PRESENT:
{
// DO SOMETHING
break;
}
case LOGIN_MESSAGE:
{
Serial.println("NOTICE: Logged IN");
this->loggedIn=true;
break;
}
case MSG_CARD:
{
Serial.println("ACK MSG_CARD Received");
if(*statusResponse==1){
Serial.println("DO EXECUTE MSG-UP");
result=this->executeMessageUp(*eventType, *packetNumber);
}
else {
//DO SOMETHING
}
break;
}
case MSG_BOLLARD_ACTIVATION:
{
Serial.print("STATUS OF THE RESPONSE ");Serial.println(*statusResponse); // 0 ERROR *statusResponse changed it's value.
if(*statusResponse==1) {
if(!this->isActive)checkBollardStatusWaitingTime=CHECK_BOLLARD_STATUS_TIME+1; // set bolard to active
this->isActive=true;
}
else{
if(this->isActive)checkBollardStatusWaitingTime=CHECK_BOLLARD_STATUS_TIME+1; // check againg the status
this->isActive=false;
}
break;
}
default:{
Serial.print("NOT CODED EVENT "); Serial.println(*eventType);
result->type=0;
#ifdef DEBUG_MODE
Serial.println("Default Message Expired");
#endif
break;
}
}
delete statusResponse;
delete eventType;
delete commandType;
delete packetNumber;
return result;
}
Hope someone can help.
Tx for your time.

Following the suggestion of TinyT i've declared commandResult* result as commandResult result = new commandResult; and changed the rest of code of consequence and ofc deleting it at the end to prevent a memory leak.
That was the variable that was creating the memory problems.
Tx TinyT

Related

Memory issue with using C++ Protobuf in a DLL

This question was posted on Google Group's Protobuf group but unfortunately it has gone unanswered.
A DLL has been created that will accept any Protobuf message which through the use of reflection will be filled with data from a database and then returned to the client. The database table name is mapped to the message name and the corresponding table columns are mapped to the message member names.
The issue appears to be with the 'SetString' method of the reflection class. After the call to the DLL has been made and the protobuf message with all the relevant has been received, a memory error is encountered as the program exists.
A typical message will have a .proto file such as the following:
message OperatingSystemInfo {
string manufacturer;
string name;
string release;
string osversion;
string localename;
string bootdevice;
string serialnumber;
}
The code snippets for the DLL functions are as follow:
void EXPORT_DLL ReadMessage(void* protoBufMessage) {
Message* msg = static_cast<Message*>(protoBufMessage);
const Descriptor* descriptor = msg->GetDescriptor();
const Reflection* reflection = msg->GetReflection();
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
const FieldDescriptor::Type type = field->type();
bool isRepeated = field->is_repeated();
std::string name = field->name();
if (type == FieldDescriptor::TYPE_MESSAGE) {
}
else {
//read values from database for each corresponding field and set value
string fieldValue;
SetFieldValues(reflection, field, msg, fieldValue);
}
}
}
void SetFieldValues(const google::protobuf::Reflection reflection,
const google::protobuf::FieldDescriptor field,
google::protobuf::Message msg,
std::string fieldValue) {
switch (field->type()) {
case FieldDescriptor::TYPE_STRING:
reflection->SetString(msg, field, move(fieldValue))
break;
case FieldDescriptor::TYPE_UINT32:
break;
case FieldDescriptor::TYPE_UINT64:
break;
case FieldDescriptor::TYPE_BOOL:
break;
case FieldDescriptor::TYPE_ENUM:
break;
default:
break;
}
}
The client call to the DLL is:
void CallDLL()
{
OperatingSystemInfo* osi = new OperatingSystemInfo();
ReadMessage(osi);
delete osi;
}
The problem is that when the application is about to terminate, the 'Destroy' method for the last string in the message, 'serialnumber', causes a memory error (__acrt_first_block == header in debug_heap.ccp):
inline void OperatingSystemState::SharedDtor() {
GOOGLE_DCHECK(GetArenaForAllocation() == nullptr);
_impl_.manufacturer_.Destroy();
_impl_.name_.Destroy();
_impl_.release_.Destroy();
_impl_.osversion_.Destroy();
_impl_.localename_.Destroy();
_impl_.bootdevice_.Destroy();
_impl_.serialnumber_.Destroy();
}
void ArenaStringPtr::Destroy() {
//Line 233 in arenastring.cc
//leads to assertion Expession: __acrt_first_block == header in debug_heap.ccp
delete tagged_ptr_.GetIfAllocated();
}
Naturally this is an attempt to free an already freed memory. It is likely that allocating the memory outside of the DLL is a factor but the nature of the project is such that the DLL has no knowledge of Protobuf message types. Hence the reason that reflection is used.
Any helps or hints in resolving this issue is greatly appreciated.

xlCanTransmit() function does not work properly

I am trying to send CAN Frames with xlCanTransmit method. The problem is that it returns 0 (XL_SUCCESS), but the frame is empty. there are only zeroes in the Frame.
IVxlApi.s_xl_event eventMsg = new IVxlApi.s_xl_event();
...
...
xlStatus = dll.xlCanTransmit(GlobalConfig.g_xlPortHandle, GlobalConfig.g_xlChannelMask[channelIndex],
pEventCount, eventMsg.getPointer());
After Calling the function xlCanTransmit() the frame is sent, but there is no data in it. The function is called from dll file and you can't debug it.
My mapped Structure
public static class s_xl_event extends Structure {
public byte tag;
public byte chanIndex;
public byte[] transId = new byte[SHORT];
public byte[] portHandle = new byte[SHORT];
public byte flags;
public byte reserved;
public byte[] timeStamp = new byte[LONG];
public s_xl_tag_data tagData;
#Override
public void read() {
// read from native memory, populate tag
super.read();
// set union type based on tag
switch (tag) {
case XL_RECEIVE_MSG:
case XL_TRANSMIT_MSG:
tagData.setType(s_xl_can_msg.class);
break;
case XL_CHIP_STATE:
tagData.setType(s_xl_chip_state.class);
break;
case XL_LIN_MSG:
tagData.setType(s_xl_lin_msg_api.class);
break;
case XL_SYNC_PULSE:
tagData.setType(s_xl_sync_pulse.class);
break;
case XL_RECEIVE_DAIO_DATA:
tagData.setType(s_xl_daio_data.class);
break;
case XL_TRANSCEIVER:
tagData.setType(s_xl_transceiver.class);
break;
case XL_RECEIVE_DAIO_PIGGY:
tagData.setType(s_xl_daio_piggy_data.class);
break;
case XL_KLINE_MSG:
tagData.setType(s_xl_kline_data.class);
break;
default:
// add default type or throw exception etc.
tagData.setType(s_xl_can_msg.class);
break;
}
// now read tagData from native memory
tagData.read();
}
#Override
protected List<String> getFieldOrder() {
return Arrays.asList("tag", "chanIndex", "transId", "portHandle", "flags", "reserved", "timeStamp", "tagData");
}
}
CAN Frame in CANoe Trace
enter image description here
The function on the native side looks like this
DECL_STDXL_FUNC(xlCanTransmit, XLCANTRANSMIT, (
XLportHandle portHandle,
XLaccess accessMask,
unsigned int* pEventCount,
void* pEvents)
);
My mapping in java
short xlCanTransmit(long portHandle, long accessMask, IntByReference pEventCount, Pointer pEvents);
I wrote some random data manually and called the xlCanTransmit() function.
But in CANoe trace I see only empty frame with no data and id.
My send function in java
public short send(String txID, String dlc, String[] data, int channelIndex) {
short xlStatus = IVxlApi.XL_ERROR;
IntByReference pEventCount = new IntByReference(1);
IVxlApi.s_xl_event eventMsg = new IVxlApi.s_xl_event();
eventMsg.tag = IVxlApi.XL_TRANSMIT_MSG;
eventMsg.tagData.msg.id[0] = 2;// = Long.parseLong(txID);
eventMsg.tagData.msg.dlc[0] = 8;// = Short.parseShort(dlc);
eventMsg.tagData.msg.flags[0] = 0;
eventMsg.tagData.msg.data[0] = Byte.parseByte(data[0]);
eventMsg.tagData.msg.data[1] = Byte.parseByte(data[1]);
eventMsg.tagData.msg.data[2] = Byte.parseByte(data[2]);
eventMsg.tagData.msg.data[3] = Byte.parseByte(data[3]);
eventMsg.tagData.msg.data[4] = Byte.parseByte(data[4]);
eventMsg.tagData.msg.data[5] = Byte.parseByte(data[5]);
eventMsg.tagData.msg.data[6] = Byte.parseByte(data[6]);
eventMsg.tagData.msg.data[7] = Byte.parseByte(data[7]);
/*if(true){
eventMsg.tagData.msg.id |= IVxlApi.XL_CAN_EXT_MSG_ID;
}*/
eventMsg.write();
xlStatus = dll.xlCanTransmit(GlobalConfig.g_xlPortHandle, GlobalConfig.g_xlChannelMask[channelIndex],
pEventCount, eventMsg.getPointer());
eventMsg.read();
return xlStatus;
}
CAN Frame in CANoe Trace
enter image description here
After calling tagData.read() (line 475) the data initialized with zeroes
enter image description here
The return value of 0 indicates the function preformed properly on the native side, but you haven't copied the native memory back to Java.
This is normally done automatically when you pass a Structure in a function, but you have passed the Pointer to the structure instead. Your last argument is eventMsg.getPointer(). JNA doesn't know how the Pointer maps to your structure until you tell it to do so, and in the current way you're calling it requires using read() to copy the value back to JNA.
You could probably get the results you want by just executing eventMsg.read() after calling the function, but the better solition is to pass the Structure to the function in the first place and let JNA do the conversion to Pointer and auto-read() for you. Change your function call to pass eventMsg as the argument.

Using Wire.onRequest by passing a class method?

I have an Arduino sketch that will be working on an Arduino UNO and I am trying to get uno to communicate over the i2c connection with a raspberry pi.
Problem is using wire.h library where method Wire.onRequest is working just fine when I use it like this.
#include <Wire.h>
#define COMM_DELAY 50
#define SLAVE_ADDRESS 0x04
int current_rule = 0;
void initI2c() {
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveData);
}
// callback for received data
void receiveData(int byteCount) {
while (Wire.available()) {
current_rule = Wire.read();
}
}
but when I try to make this exact result with a class method, I get an error :
invalid use of non-static member function
(with Wire.onRequest(this->receiveData) line gets to be marked red)
Just like this:
void (*funptr)();
typedef void (*Callback)(byte);
class Comm{
public:
int callback_list_size = 0;
bool option_debug;
byte option_address;
int option_comm_delay;
void(*callback_list[256]);
byte *rules;
// function for receiving data. raspberry -> arduino
// Whenever the master sends new data, this method will call the appropriate callback.
void receiveData()
{
byte data;
Serial.println("[INFO] Received new data from master");
while (Wire.available())
{
data = Wire.read();
}
for (int i = 0; i < callback_list_size; i++)
{
if (rules[i] == data){
funptr = callback_list[i];
funptr();
}
}
}
// function for sending data. Called when raspberry request data. arduino -> raspberry
// Whenever the master requests data, this method will be called. For now we don't need this but anyway.
void sendData(int s)
{
if (option_debug)
Serial.println("[INFO] Master requests data!");
}
/* Constructor that takes 3 parameters at max. Only the adress is mandatory others are optional and will be filled with default values
:address - adress of slave(arduino) - Example 0x04
:delay - a delay is needed because I2C clock is quite slow compared to the CPU clock - 50
:debug - for debug purposes if true debug info will be sent to Serial interface - true/false
*/
Comm(byte address, int delay = 50, bool debug = false)
{
option_address = address;
option_comm_delay = delay;
option_debug = debug;
if (debug)
Serial.println("[INFO] Comm Object Created!");
}
// Function needs to be called to initialize the communication channel.
void initI2c()
{
Wire.begin(option_address);
Wire.onReceive(this->sendData);
Wire.onRequest(this->receiveData);
if (option_debug)
Serial.println("[INFO] I2C channel initialized");
}
// Function to add new callback for a rule.
// This function returns id of passed callback
int addCallback(Callback func, byte rule)
{
callback_list_size++;
// Enlarge rules array to keep 1 more byte
byte *temp = new byte[callback_list_size]; // create new bigger array.
for (int i = 0; i + 1 < callback_list_size; i++) // reason fo i+1 is if callback_list_size is 1 than this is the first initializition so we don't need any copying.
{
temp[i] = rules[i]; // copy rules to newer array.
}
delete[] rules; // free old array memory.
rules = temp; // now rules points to new array.
callback_list[callback_list_size - 1] = &func;
rules[callback_list_size - 1] = rule;
return callback_list_size;
}
};
Comm *i2c_comm;
void loop()
{
}
void setup()
{
Serial.begin(9600);
initI2C();
}
void initI2C()
{
i2c_comm = new Comm(0x04, 50, true);
i2c_comm->initI2c();
//Callback Definitions
i2c_comm->addCallback(&rule_1, 0x01);
i2c_comm->addCallback(&rule_2, 0x02);
i2c_comm->addCallback(&rule_3, 0x03);
i2c_comm->addCallback(&rule_4, 0x04);
}
I also tried to make the receiveData method to be static.
But in this case I have an error like this:
invalid use of member Com::callback_list_size in static member function
which makes sense to me as static method won't know which callback_list_size I am talking about.
so I am quite confused about how I can handle such a problem?
You're almost there. Generally speaking in C++ you need to pass a static class method for callback functions.
The error you received after changing your method to static is expected as you're trying to access a member of an instance of the class Comm which cannot be done in a static method in which there is no 'this'.
Here's one of many techniques to consider, but please read over the SO post Using a C++ class member function as a C callback function.
Anyway the approach here is to leverage a static pointer to an instance.
class Comm {
private:
static Comm* pSingletonInstance;
static void OnReceiveHandler() {
if (pSingletonInstance)
pSingletonInstance->receiveData();
}
static void OnSendHandler(int s) {
if (pSingletonInstance)
pSingletonInstance->sendData(s);
}
void initI2c() {
Comm::pSingletonInstance = this; // Assign the static singleton used in the static handlers.
Wire.onReceive(Comm::OnSendHandler);
Wire.onRequest(Comm::OnReceiveHandler);
Wire.begin(option_address);
}
}
// static initializer for the static member.
Comm* Comm::pSingletonInstance = 0;
Again there are many ways to get around this issue but above is an easy one and likely suitable for your project. If you need to manage multiple instances of Comm, you'll have to do something quite different.
Good luck!

How save in an array the following 100 received value after a determined received string in Qt

I'm a newbie in C++ and Qt. I want to save in an array the value received in a serialport after I received the string: "Data".
I'm using the terminal example so the serialport works properly.
The read function in the Example is the same:
void MainWindow::readData()
{
QByteArray data = serial->readAll();
console->putData(data);
}
How can I modify it? thanks!!!
If your manual sending the data i recommend you add a start of frame delimiter and an end of frame delimiter and checksum preferably.
QByteArray packet_storage;
just declare it the where you declare serial.
StartOfMessage and EndOfMessage will depend on your device.
I don't know what your transmitting. Hopefully you can figure out from the documentation of your device what your sending out.
as for me i am using
enum Constants
{
StartOfMessage = '\x02', /* Value of byte that marks the start of a message */
EndOfMessage = '\x03', /* Value of byte that marks the end of a message */
CarridgeReturn = '\x0D', /* Carridge return is first byte of end of line */
LineFeed = '\x0A', /* Line feed is second byte of end of line */
NullChar = '\0' /* Null Character */
};
void MainWindow::readData()
{
// read all
QByteArray data = serial->readAll();
// store all read data packet_storage is a QByteArray
packet_storage.append(data);
int start_index = 0;
int end_index = 0;
// process packet if not empty
if(!packet_storage.isEmpty())
{
if( packet_storage.contains(StartOfMessage) && packet_storage.contains(EndOfMessage))
{
start_index = packet_storage.indexOf(StartOfMessage,0);
end_index = packet_storage.indexOf(EndOfMessage,0);
int length = 0;
for (int i=start_index; i <= end_index; i++)
{
length++;
}
// get data
QByteArray dt = packet_storage.mid(start_index,length);
// do your processing here.
// store in vector write to file etc.
processpacket(dt);
packet_storage.remove(start_index,dt.size());
}
}
}

Threads C++, Access Violation reading location x error

Platform : Windows 7
I'm developing a project for known text cipher attack in which;
Main process creates n child processes
Child processes decrypt an encrypted string, key subspace is partitioned according to number of child processes
Communication between child processes are by a static variable
for(int i = 0; i<info.totalNumberOfChildren; i++)
{
startChild( &info.childInfoList[i]);
//_beginthread(startChild, 0, &info.childInfoList[i]);
}
Above code works fine since:
First child starts execution, the key is set as a number such as 8 for testing purposes which is within the first child's partition, so first child finds the key, reports and sets true the killSwitch.
All the other children that are created are closed even before checking the first key as the killSwitch is true.
When I however do this :
for(int i = 0; i<info.totalNumberOfChildren; i++)
{
//startChild( &info.childInfoList[i]);
_beginthread(startChild, 0, &info.childInfoList[i]);
}
I get an access violation error. What could possibly be my source of error ?
Edit: I will try to share as relevant code as I can
startChild does the following:
void startChild( void* pParams)
{
ChildInfo *ci = (ChildInfo*)pParams;
// cout<<"buraya geldi"<<endl;
ChildProcess cp(*ci);
// write to log
cp.completeNextJob();
}
childInfo holds the following :
// header file
class ChildInfo
{
public:
ChildInfo();
ChildInfo(char * encrypted, char * original, static bool killSwitch, int totalNumOfChildren, int idNum, int orjLen);
void getNextJob();
bool keyIsFound();
Des des;
void printTest();
bool stopExecution;
bool allIsChecked;
char * encyptedString;
char * originalString;
int id;
int orjStrLen;
private:
int lastJobCompleted;
int totalNumberOfChildren;
int jobDistBits;
};
completeNextJob() does the following :
void ChildProcess::completeNextJob()
{
cout<<"Child Id : "<<info.id<<endl;
// cout<<"Trying : "<<info.encyptedString<<endl; // here I got an error
char * newtrial = info.encyptedString;
char * cand = info.des.Decrypt(newtrial); // here I also get an error if I comment out
/*
cout<<"Resultant : "<<cand<<endl;
cout<<"Comparing with : "<<info.originalString<<endl;
*/
bool match = true;
for(int i = 0; i<info.orjStrLen; i++)
{
if(!(cand[i] == info.originalString[i]))
match = false;
}
if(match)
{
cout<<"It has been acknowledged "<<endl;
info.stopExecution = true;
return;
}
else
{
if(!info.keyIsFound())
{
if(!info.allIsChecked)
{
info.getNextJob();
completeNextJob();
}
else
{
}
}
else
{
}
}
}
decrypt() method does the following :
char * Des::Decrypt(char *Text1)
{
int i,a1,j,nB,m,iB,k,K,B[8],n,t,d,round;
char *Text=new char[1000];
unsigned char ch;
strcpy(Text,Text1); // this is where I get the error
i=strlen(Text);
keygen();
int mc=0;
for(iB=0,nB=0,m=0;m<(strlen(Text)/8);m++) //Repeat for TextLenth/8 times.
{
for(iB=0,i=0;i<8;i++,nB++)
{
ch=Text[nB];
n=(int)ch;//(int)Text[nB];
for(K=7;n>=1;K--)
{
B[K]=n%2; //Converting 8-Bytes to 64-bit Binary Format
n/=2;
} for(;K>=0;K--) B[K]=0;
for(K=0;K<8;K++,iB++) total[iB]=B[K]; //Now `total' contains the 64-Bit binary format of 8-Bytes
}
IP(); //Performing initial permutation on `total[64]'
for(i=0;i<64;i++) total[i]=ip[i]; //Store values of ip[64] into total[64]
for(i=0;i<32;i++) left[i]=total[i]; // +--> left[32]
// total[64]--|
for(;i<64;i++) right[i-32]=total[i];// +--> right[32]
for(round=1;round<=16;round++)
{
Expansion(); //Performing expansion on `right[32]' to get `expansion[48]'
xor_oneD(round);
substitution();//Perform substitution on xor1[48] to get sub[32]
permutation(); //Performing Permutation on sub[32] to get p[32]
xor_two(); //Performing XOR operation on left[32],p[32] to get xor2[32]
for(i=0;i<32;i++) left[i]=right[i]; //Dumping right[32] into left[32]
for(i=0;i<32;i++) right[i]=xor2[i]; //Dumping xor2[32] into right[32]
} //rounds end here
for(i=0;i<32;i++) temp[i]=right[i]; // Dumping -->[ swap32bit ]
for(;i<64;i++) temp[i]=left[i-32]; // left[32],right[32] into temp[64]
inverse(); //Inversing the bits of temp[64] to get inv[8][8]
/* Obtaining the Cypher-Text into final[1000]*/
k=128; d=0;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
d=d+inv[i][j]*k;
k=k/2;
}
final[mc++]=(char)d;
k=128; d=0;
}
} //for loop ends here
final[mc]='\0';
char *final1=new char[1000];
for(i=0,j=strlen(Text);i<strlen(Text);i++,j++)
final1[i]=final[j]; final1[i]='\0';
return(final);
}
Windows is trying to tell you why your program crashed. Please use a debugger to see what Windows is talking about. Location X is important: it should tell you whether your program is dereferencing NULL, overflowing a buffer, or doing something else. The call stack at the time of the crash is also very important.
Debugger is your best friend, try to use it and check step by step what could cause this access violation.
I think that info.encyptedString is not initialized correctly and pointing to not allocated memory, but I cant be sure because you didn't show this part of code.
And of course you must protect your shared resources (info) using some synchronization objects like critical section or mutex or semaphore.
I don't know, the basic issue seems pretty straightforward to me. You have multiple threads executing simultaneously, which access the same information via *pParams, which presumably is of type ChildInfo since that's what you cast it to. That info must be getting accessed elsewhere in the program, perhaps in the main thread. This is corrupting something, which may or may not have to do with Text1 or info.id, these errors can often be 'non-local' and hard to debug for this reason. So start mutex-protecting the entire thread (within your initial loop), and then zero in on the critical sections by trial and error, i.e. mutex-protect as small a region of code as you can get away with without producing errors.