I am a llvm newbie.
I am trying to write a llvm pass to optimize for algebraic identities in a function (like, if my function has an instruction a = b * 0, my pass should replace all following uses of "a" with 0).
So, my pass looks like follows:-
...
for (Function::iterator f_it = F.begin(), f_ite = F.end(); f_it != f_ite; ++f_it) {
for(BasicBlock::iterator b_it = f_it->begin(), b_ite = f_it->end(); b_it != b_ite; ++b_it) {
if(op->getOpcode() == Instruction::Mul) {
if(ConstantInt *CI_F = dyn_cast<ConstantInt>(&*b_it->getOperand(0))) {
if(CI_F->isZero()) {
firstop_zero = 1;
}
}
if(ConstantInt *CI_S = dyn_cast<ConstantInt>(&*b_it->getOperand(1))) {
if(CI_S->isZero()) {
secop_zero = 1;
}
}
if(first_zero || second_zero) {
errs()<<"found zero operand\n";
ReplaceInstWithValue(b_it->getParent()->getInstList(),b_it,(first_zero?(&*b_it->getOperand(1)):(&*b_it->getOperand(0))));
}
}
}
}
I can see that my comment "found zero operand gets printed out on std-err, but I can't see the replacement in the resulting .bc's disassembly.
What am I missing here? Any help is sincerely appreciated.
Thanks a lot!
Praveena
Try
for (Function::iterator f_it = F.begin(), f_ite = F.end(); f_it != f_ite; ++f_it) {
for(BasicBlock::iterator b_it = f_it->begin(), b_ite = f_it->end(); b_it != b_ite; ++b_it) {
Instruction *I = *b_it;
Value *Zeroval;
if(op->getOpcode() == Instruction::Mul) {
if(ConstantInt *CI_F = dyn_cast<ConstantInt>(&*b_it->getOperand(0))) {
if(CI_F->isZero()) {
firstop_zero = 1;
Zeroval = CI_F;
}
}
if(ConstantInt *CI_S = dyn_cast<ConstantInt>(&*b_it->getOperand(1))) {
if(CI_S->isZero()) {
secop_zero = 1;
ZeroVal = CI_S;
}
}
if(first_zero || second_zero) {
errs()<<"found zero operand\n";
I->ReplaceAlluseswith(ZeroVal);
}
}
}
}
Related
This could be a basic question, however, I couldn't figure out how can I simplify this statement. I have a feeling that something's not right on this code.
Thank you.
var a = string.Empty;
if (File.Exists(a = Path.Combine(modelPath, "attributes", filename))) { }
else
{
if (File.Exists(a = GetSaveAsAttribute(firmPath))) { }
else
{
for (int i = 0; i < systemPaths.Count; i++)
{
if (File.Exists(a = GetSaveAsAttribute(systemPaths[i])))
break;
}
}
}
You can remove your **if** by directly checking for another condition.
var a = string.Empty;
if (!(File.Exists(a = Path.Combine(modelPath, "attributes", filename)))) {
if (!(File.Exists(a = GetSaveAsAttribute(firmPath))) ){
for (int i = 0; i < systemPaths.Count; i++)
{
if (File.Exists(a = GetSaveAsAttribute(systemPaths[i])))
break;
}
}
}
Hello, i was solving this -> kata on CodeWars.
I am using a VusialStudio 2019 to write code. When i start this project in VS no erros is presented to me. The program even works correctly for the first test case. But when i am testing it on problem's page it gives me an error:
UndefinedBehaviorSanitizer:DEADLYSIGNAL
==1==ERROR: UndefinedBehaviorSanitizer: SEGV on unknown address 0x000000000000 (pc 0x000000429d24 bp 0x7ffc2f3f72b0 sp 0x7ffc2f3f7150 T1)
==1==The signal is caused by a READ memory access.
==1==Hint: address points to the zero page.
==1==WARNING: invalid path to external symbolizer!
==1==WARNING: Failed to use and restart external symbolizer!
#0 0x429d23 (/workspace/test+0x429d23)
#1 0x42ab1d (/workspace/test+0x42ab1d)
#2 0x429fa3 (/workspace/test+0x429fa3)
#3 0x42e2f2 (/workspace/test+0x42e2f2)
#4 0x42c9ce (/workspace/test+0x42c9ce)
#5 0x42c529 (/workspace/test+0x42c529)
#6 0x42c11b (/workspace/test+0x42c11b)
#7 0x431425 (/workspace/test+0x431425)
#8 0x42a08d (/workspace/test+0x42a08d)
#9 0x7f1b94116bf6 (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6)
#10 0x4053e9 (/workspace/test+0x4053e9)
UndefinedBehaviorSanitizer can not provide additional info.
==1==ABORTING
For a while i was turning on and off parts of program to determen where the problem is. I nereved it down to this line
Program::Status_enum Program::ExecuteComand(Comand_Class* ComandToExe)
{
else if (ComandToExe->name == "div")
{
this->Registers[ComandToExe->args[0]] /= GetValue(ComandToExe->args[1]); // error here
}
}
Leter i found out that error was showing up even if i chage line to
this->Registers.begin()->second = 3; // same error
this->Registers["a"] = 2; // same error
It looks to me that any change of value causes it to throw an error. But reaading for example was ok
int a = Registers["a"];
std::cout << a; // will print a right value
So this basikly all i was able to find out by my self. Here is structer of my code.
Basikly my goal is to write a Asmbler intorpritator
// All Comands saved as this class
class Comand_Class
{
public:
std::string name; // for example mov, div, etc.
std::vector<std::string> args; // data for the comand
Comand_Class(std::string Name, std::string arg1 = "", std::string arg2 = "")
{
//..
}
Comand_Class(std::string Name, std::vector<std::string> Args)
{
//..
}
};
// I use this class to store functions cod as a small program itself
class Function_Class
{
public:
std::vector<Comand_Class*> FunctionProgram;
};
// the main class
class Program
{
std::string MSG = "-1"; // for outout
std::unordered_map <std::string, int> Registers; // map in which the problem exsist
std::vector<Comand_Class*> ProgramLines; // Starting code
std::map<std::string,Function_Class*> CallList; // Name of Function and Her code to exe
// .exe is giving me back the status, after executing a Comand_Class line, this how i know what to do next.
enum Status_enum
{
END = 0,
CALL = 1,
JUMP = 2,
RET = 3,
CONTINUE = 10,
ERROR = -1,
};
public:
std::string Start()
{
exe(this -> ProgramLines );
return MSG;
}
int GetValue(std::string arg)
{
if ('a' <= arg[0] && arg[0] <= 'z')
{
//register
return this->Registers[arg];
}
else
{
int a = std::stoi(arg);
return a;
}
}
// not related to the problem,
void preprocesing(std::string program);
Status_enum ExecuteComand(Comand_Class* ComandToExe);
void exe(std::vector<Comand_Class*> ProgramLinesToExe);
~Program()
{
for (unsigned long i = 0; i < ProgramLines.size(); i++)
{
Comand_Class* del = ProgramLines.at(i);
delete del;
}
for (auto it = CallList.begin(); it != CallList.end(); it++)
{
for (unsigned long i = 0; i < it->second->FunctionProgram.size(); i++)
{
Comand_Class* del = it->second->FunctionProgram.at(i);
delete del;
}
}
// add CallList to clear
}
};
// this function is recurseve, Can this be a reson why it brakes?
void Program::exe(std::vector<Comand_Class*> ProgramLinesToExe)
{
Status_enum Status;
unsigned long int SubPC = 0; // Comand to exe
while (SubPC < ProgramLinesToExe.size())
{
Status = ExecuteComand(ProgramLinesToExe[SubPC]);
if (Status != CONTINUE)
{
if(Status == JUMP)
{
exe(CallList[ProgramLinesToExe[SubPC]->args[0]]->FunctionProgram);
}
else if (Status == CALL)
{
auto test = CallList[ProgramLinesToExe[SubPC]->args[0]]->FunctionProgram;
exe(CallList[ProgramLinesToExe[SubPC]->args[0]]->FunctionProgram);
}
else if (Status == RET)
{
return;
}
else if (Status == END)
{
break;
}
else if (Status == ERROR)
{
std::cout << "Unknown comand! " << ProgramLinesToExe[SubPC]->name;
}
}
SubPC++;
}
}
// Untill this function called second time (recursively) all works good
Program::Status_enum Program::ExecuteComand(Comand_Class* ComandToExe)
{
if (ComandToExe->name == "mov")
{
this->Registers[ComandToExe->args[0]] = GetValue(ComandToExe->args[1]);
}
else if (ComandToExe->name == "inc")
{
this->Registers[ComandToExe->args[0]]++;
}
else if (ComandToExe->name == "dec")
{
this->Registers[ComandToExe->args[0]]--;
}
else if (ComandToExe->name == "add")
{
this->Registers[ComandToExe->args[0]] += GetValue(ComandToExe->args[1]);
}
else if (ComandToExe->name == "sub")
{
this->Registers[ComandToExe->args[0]] -= GetValue(ComandToExe->args[1]);
}
else if (ComandToExe->name == "mil")
{
this->Registers[ComandToExe->args[0]] *= GetValue(ComandToExe->args[1]);
}
else if (ComandToExe->name == "div")
{
//this->Registers[ComandToExe->args[0]] /= GetValue(ComandToExe->args[1]); error
}
else if (ComandToExe->name == "cmp")
{
int x = GetValue(ComandToExe->args[0]);
int y = GetValue(ComandToExe->args[1]);
this->CompareFlugs.Equal = (x == y);
this->CompareFlugs.Less = (x < y);
}
else if (ComandToExe->name == "jne") // if the values of the previous cmp command were not equal.
{
if (this->CompareFlugs.Equal == false)
{
return JUMP;
}
}
else if (ComandToExe->name == "je") // if the values of the previous cmp command were equal.
{
if (this->CompareFlugs.Equal == true)
{
return JUMP;
}
}
else if (ComandToExe->name == "jge") // if x was greater or equal than y in the previous cmp command.
{
if (this->CompareFlugs.Less == false)
{
return JUMP;
}
}
else if (ComandToExe->name == "jg") // f x was greater than y in the previous cmp command.
{
if ((this->CompareFlugs.Less == false) && (this->CompareFlugs.Equal == false))
{
return JUMP;
}
}
else if (ComandToExe->name == "jle") // if x was less or equal than y in the previous cmp command.
{
if ((this->CompareFlugs.Less == true) || (this->CompareFlugs.Equal == true))
{
return JUMP;
}
}
else if (ComandToExe->name == "jl") // if x was less than y in the previous cmp command.
{
if (this->CompareFlugs.Less == true)
{
return JUMP;
}
}
else if (ComandToExe->name == "call")
{
return CALL;
}
else if (ComandToExe->name == "ret")
{
return RET;
}
else if (ComandToExe->name == "end")
{
return END;
}
else if (ComandToExe->name == "msg")
{
MSG = "";
for (unsigned long int i = 0; i < ComandToExe->args.size(); i++)
{
if (ComandToExe->args[i][0] == '\'')
{
MSG += ComandToExe->args[i].substr(1);
}
else
{
MSG += std::to_string(GetValue(ComandToExe->args[i]));
}
}
}
else
{
return ERROR;
}
return CONTINUE;
}
That's all. Also i am new to stackoverflow, so if i did somting very bad, do not judge strictly.
And Here all the code, becase i cut parts i think was usless:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <unordered_map>
#include <regex>
class Comand_Class
{
public:
std::string name;
std::vector<std::string> args;
Comand_Class(std::string Name, std::string arg1 = "", std::string arg2 = "")
{
name = Name;
args.push_back(arg1);
if (!arg2.empty())
{
args.push_back(arg2);
}
}
Comand_Class(std::string Name, std::vector<std::string> Args)
{
name = Name;
args = Args;
}
};
class Function_Class
{
public:
//Comand_Class* ReturnControlTo = NULL;
std::vector<Comand_Class*> FunctionProgram;
};
class Program
{
//int PC = 0;
std::string MSG = "-1";
std::unordered_map <std::string, int> Registers;
std::vector<Comand_Class*> ProgramLines;
std::map<std::string,Function_Class*> CallList;
class CompareFlugs_Class
{
public:
bool Less = false;
bool Equal = false;
}CompareFlugs;
enum Status_enum
{
END = 0,
CALL = 1,
JUMP = 2,
RET = 3,
CONTINUE = 10,
ERROR = -1,
};
const std::string AllowedCommands = "mov inc dev add sub mul div cmp";
public:
std::string Start()
{
exe(this -> ProgramLines );
return MSG;
}
int GetValue(std::string arg)
{
if ('a' <= arg[0] && arg[0] <= 'z')
{
//register
return this->Registers[arg];
}
else
{
int a = std::stoi(arg);
return a;
}
}
void preprocesing(std::string program);
Status_enum ExecuteComand(Comand_Class* ComandToExe);
void exe(std::vector<Comand_Class*> ProgramLinesToExe);
~Program()
{
for (unsigned long i = 0; i < ProgramLines.size(); i++)
{
Comand_Class* del = ProgramLines.at(i);
delete del;
}
for (auto it = CallList.begin(); it != CallList.end(); it++)
{
for (unsigned long i = 0; i < it->second->FunctionProgram.size(); i++)
{
Comand_Class* del = it->second->FunctionProgram.at(i);
delete del;
}
}
// add CallList to clear
}
};
void Program::preprocesing(std::string program)
{
std::string read;
Comand_Class*NewProgramLine;
std::istringstream iss(program);
std::smatch matches;
std::regex Comand(";(.*)|call\\s(.*)|(end|ret)|msg(.*)[;]?|(\\w+):|(j\\w{1,2})\\s+(\\w+)|(\\w+)\\s+(\\w),?\\s?(\\d+|\\w)?");
bool WtireToFunction = false;
std::string ActiveLabel;
Function_Class* NewFunction = nullptr;// = new Function_Class;
while (!iss.eof())
{
std::getline(iss, read);
std::regex_search(read, matches, Comand);
/*
if (matches.size() != 0)
std::cout << "Comand is " << matches[0] << "\n";
*/
// parcing
std::string Coment = matches[1];
std::string CallLabel = matches[2];
std::string End = matches[3];
std::string Message = matches[4]; // may contain a comment in the end
std::string Label = matches[5];
std::string JumpComand = matches[6];
std::string JumpLabel = matches[7];
std::string ComandName = matches[8];
std::string arg1 = matches[9];
std::string arg2 = matches[10];
if ((!ComandName.empty()) && (AllowedCommands.find(ComandName) != std::string::npos))
{
//std::cout << "Comand is " << matches[0] << "\n";
std::cout << "Comand is " << ComandName << " " << arg1 << " " << arg2 << "\n";
NewProgramLine = new Comand_Class (ComandName,arg1,arg2);
//NewProgramLine->name = ComandName;
//NewProgramLine->args.push_back(arg1);
if (WtireToFunction == false)
{
this->ProgramLines.push_back(NewProgramLine);
}
else
{
NewFunction->FunctionProgram.push_back(NewProgramLine);
}
}
else if (!JumpComand.empty()) // && (AllowedJumpComands.find(JumpComand) != std::string::npos))
{
std::cout << "Comand is " << JumpComand << " " << JumpLabel << "\n";
NewProgramLine = new Comand_Class(JumpComand, JumpLabel);
}
else if (!CallLabel.empty()) // on call
{
NewProgramLine = new Comand_Class("call", CallLabel);
this->ProgramLines.push_back(NewProgramLine); // add Call to the ProgramLines
}
else if (!Label.empty()) // Generate New SubProgram
{
WtireToFunction = true;
ActiveLabel = Label;
NewFunction = new Function_Class;
this->CallList[ActiveLabel] = NewFunction;
}
else if (!Message.empty())
{
std::regex MessageParcing("('.*)'|,\\s(\\w)");
std::smatch matches;
std::sregex_iterator it(Message.begin(), Message.end(), MessageParcing), end;
std::vector<std::string> args;
while (it!= end)
{
matches = *it;
if (!matches[1].str().empty())
{
args.push_back(matches[1].str());
}
else if (!matches[2].str().empty())
{
args.push_back(matches[2].str());
}
else
{
std::cout << "Error: cannot format msg\n";
}
it++;
}
NewProgramLine = new Comand_Class("msg",args);
this->ProgramLines.push_back(NewProgramLine);
}
else if (!End.empty())
{
if (End == "end")
{
NewProgramLine = new Comand_Class("end");
this->ProgramLines.push_back(NewProgramLine); // add Call to the ProgramLines
}
if (End == "ret")
{
if (NewFunction == nullptr)
std::cout << "No Call Detected, but ret is found\n";
else
{
NewProgramLine = new Comand_Class("ret");
NewFunction->FunctionProgram.push_back(NewProgramLine);
}
}
}
}
}
Program::Status_enum Program::ExecuteComand(Comand_Class* ComandToExe)
{
if (ComandToExe->name == "mov")
{
this->Registers[ComandToExe->args[0]] = GetValue(ComandToExe->args[1]);
}
else if (ComandToExe->name == "inc")
{
this->Registers[ComandToExe->args[0]]++;
}
else if (ComandToExe->name == "dec")
{
this->Registers[ComandToExe->args[0]]--;
}
else if (ComandToExe->name == "add")
{
this->Registers[ComandToExe->args[0]] += GetValue(ComandToExe->args[1]);
}
else if (ComandToExe->name == "sub")
{
this->Registers[ComandToExe->args[0]] -= GetValue(ComandToExe->args[1]);
}
else if (ComandToExe->name == "mil")
{
this->Registers[ComandToExe->args[0]] *= GetValue(ComandToExe->args[1]);
}
else if (ComandToExe->name == "div")
{
int a = GetValue(ComandToExe->args[1]);
auto t = ComandToExe->args[0];
int b = 6 / 2;
this->MSG = "Hi";
this->Registers[t] = b;
this->Registers.begin()->second = 3;
//this->Registers[ComandToExe->args[0]] /= GetValue(ComandToExe->args[1]);
}
else if (ComandToExe->name == "cmp")
{
int x = GetValue(ComandToExe->args[0]);
int y = GetValue(ComandToExe->args[1]);
this->CompareFlugs.Equal = (x == y);
this->CompareFlugs.Less = (x < y);
}
else if (ComandToExe->name == "jne") // if the values of the previous cmp command were not equal.
{
if (this->CompareFlugs.Equal == false)
{
return JUMP;
}
}
else if (ComandToExe->name == "je") // if the values of the previous cmp command were equal.
{
if (this->CompareFlugs.Equal == true)
{
return JUMP;
}
}
else if (ComandToExe->name == "jge") // if x was greater or equal than y in the previous cmp command.
{
if (this->CompareFlugs.Less == false)
{
return JUMP;
}
}
else if (ComandToExe->name == "jg") // f x was greater than y in the previous cmp command.
{
if ((this->CompareFlugs.Less == false) && (this->CompareFlugs.Equal == false))
{
return JUMP;
}
}
else if (ComandToExe->name == "jle") // if x was less or equal than y in the previous cmp command.
{
if ((this->CompareFlugs.Less == true) || (this->CompareFlugs.Equal == true))
{
return JUMP;
}
}
else if (ComandToExe->name == "jl") // if x was less than y in the previous cmp command.
{
if (this->CompareFlugs.Less == true)
{
return JUMP;
}
}
else if (ComandToExe->name == "call")
{
// написать адресс для возврата в структуру с функциями
return CALL;
}
else if (ComandToExe->name == "ret")
{
return RET;
}
else if (ComandToExe->name == "end")
{
return END;
}
else if (ComandToExe->name == "msg")
{
MSG = "";
for (unsigned long int i = 0; i < ComandToExe->args.size(); i++)
{
if (ComandToExe->args[i][0] == '\'')
{
MSG += ComandToExe->args[i].substr(1);
}
else
{
MSG += std::to_string(GetValue(ComandToExe->args[i]));
}
}
}
else
{
return ERROR;
}
return CONTINUE;
}
void Program::exe(std::vector<Comand_Class*> ProgramLinesToExe)
{
Status_enum Status;
unsigned long int SubPC = 0;
while (SubPC < ProgramLinesToExe.size())
{
Status = ExecuteComand(ProgramLinesToExe[SubPC]);
if (Status != CONTINUE)
{
if(Status == JUMP)
{
exe(CallList[ProgramLinesToExe[SubPC]->args[0]]->FunctionProgram);
}
else if (Status == CALL)
{
auto test = CallList[ProgramLinesToExe[SubPC]->args[0]]->FunctionProgram;
exe(CallList[ProgramLinesToExe[SubPC]->args[0]]->FunctionProgram);
}
else if (Status == RET)
{
return;
}
else if (Status == END)
{
break;
}
else if (Status == ERROR)
{
std::cout << "Unknown comand! " << ProgramLinesToExe[SubPC]->name;
}
}
SubPC++;
}
}
std::string assembler_interpreter(std::string program)
{
Program Main;
Main.preprocesing(program);
return Main.Start();
}
while( !q.is_empty() )
{
loc = q.remove_from_front();
//cout << loc.row << " " << loc.col << endl;
if( (loc.row-1) >= 0) //north
{
loc2.row = loc.row-1;
loc2.col = loc.col;
if(maze[loc2.row][loc2.col] != '#' && visited[loc2.row][loc2.col] == false)
{
visited[loc2.row][loc2.col] = true;
q.add_to_back(loc2);
//loc = predecessor[loc.row][loc.col];
predecessor[loc2.row][loc2.col] = loc;
if(maze[loc2.row][loc2.col] == 'F')
{
result = 1;
maze[loc2.row][loc2.col] = '*';
break;
}
}
}
if(loc.col-1 >= 0) //West
{
loc2.row = loc.row;
loc2.col = loc.col-1;
if(maze[loc2.row][loc2.col] != '#' && visited[loc2.row][loc2.col] == false)
{
visited[loc2.row][loc2.col] = true;
q.add_to_back(loc2);
//loc = predecessor[loc.row][loc.col];
predecessor[loc2.row][loc2.col] = loc;
if(maze[loc2.row][loc2.col] == 'F')
{
result = 1;
maze[loc2.row][loc2.col] = '*';
break;
}
}
}
if(loc.row+1 < rows) //South
{
loc2.row = loc.row+1;
loc2.col = loc.col;
if(maze[loc2.row][loc2.col] != '#' && visited[loc2.row][loc2.col] == false)
{
visited[loc2.row][loc2.col] = true;
q.add_to_back(loc2);
// loc = predecessor[loc.row][loc.col];
predecessor[loc2.row][loc2.col] = loc;
if(maze[loc2.row][loc2.col] == 'F')
{
result = 1;
maze[loc2.row][loc2.col] = '*';
break;
}
}
}
if(loc.col+1 < cols) //East
{
loc2.row = loc.row;
loc2.col = loc.col+1;
if(maze[loc2.row][loc2.col] != '#' && visited[loc2.row][loc2.col] == false)
{
visited[loc2.row][loc2.col] = true;
q.add_to_back(loc2);
//loc = predecessor[loc.row][loc.col];
predecessor[loc2.row][loc2.col] = loc;
if(maze[loc2.row][loc2.col] == 'F')
{
result = 1;
maze[loc.row][loc.col] = '*';
break;
}
}
}
}
if(result == 1)
{
while()
{
//not sure...
}
}
This is my BFS algorithm and the main reason I asked this question is because the other questions similar to my own question tends to be done with vectors. I haven't learn vectors yet. What I am trying to do is to print the shortest path using '' characters to display it on valid elements. It should be in bounds, no walls visited (walls are '#' characters), and no element should be visited twice. I know that if I set my predecessor 2D array correctly, the shortest path should be displayed correctly. However, I am not sure if I did set it up correctly and how to actually fill in that path with '' characters...
I've got an issue with an Object array in an object:
I have a class with an object array:
class element
{
public:
element() {};
LinePiece* arrayLP;
and I have a class thats in the array:
class LinePiece
{
public:
LinePiece() {};
AnsiString Type;
int ElementNr;
int Status;
int X, Y;
so within the Element object I have a LinePiece array. The odd thing is, when I fill in ElementArray[1].LPArray[0]; it gets overwritten by the next object (ElementArray[2].LPArray[0];
I fill it with the following code:
String FileBuffer;
String Regel;
String Code;
element* GetElementInfo()
{
//alle onderdelen van een Elementobject
String OrderNumber; //ON
String OrderBrand; //MO
String ElementNumber; //SN
String ElementMarking; //RS
String ReinforcementPattern; //OW
String CalculationNumber; //CN
String ElementLength; //LE
String ElementWidth; //WD
String ElementBeginX; //BP
String ConcreteThickness; //TH
String Isulation; //IH
String Weight; //NW
element *ElementArray = new element[100];
LinePiece *LPArray = new LinePiece[100];
bool firstElement = true;
int Index =0;
int LPIndex = 0;
for(int i = 1; i <= FileBuffer.Length(); i++)
{
if(FileBuffer[i] != 0)
{
if(FileBuffer[i] != IntToStr('\r')) //controleren of je op einde regel zit, zoniet vul de string "regel" aan
{
if(FileBuffer[i] != IntToStr('\r') && FileBuffer[i] != IntToStr('\n'))
{
Regel = Regel + FileBuffer[i];
}
}
else //kijken wat er op de regel staat
{
Code = Regel.SubString(0,2);
if(Code == "ON") //Ordernummer
{
OrderNumber = Regel.SubString(4, (Regel.Length() -3));
Regel = "";
}
if(Code =="MO") //Ordermerk
{
OrderBrand = Regel.SubString(4, (Regel.Length() -3));
Regel = "";
}
if(Code =="SN") //Element nummer
{
ElementNumber = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code =="RS") //Element marking
{
ElementMarking = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code =="CN") //Calculatienummer
{
CalculationNumber = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code == "LE") //Element lengte
{
ElementLength = Regel.SubString(4,(Regel.Length()-3));
Regel = "";
}
if(Code == "WD") //element breedte
{
ElementWidth = Regel.SubString(4,(Regel.Length()-3));
Regel = "";
}
if(Code == "BP") //beginpunt X
{
ElementBeginX = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if (Code == "OW") //Wapeningspatroon
{
ReinforcementPattern = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code == "TH") //Beton dikte
{
ConcreteThickness = Regel.SubString(4,(Regel.Length()-3));
Regel = "";
}
if(Code == "IH") //isolatie dikte
{
Isulation = Regel.SubString(4,(Regel.Length()-3));
Regel = "";
}
if(Code == "NW") //Gewicht
{
Weight = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code == "CO") //Contour
{
String geheleRegel = Regel.SubString(4, (Regel.Length() -3));
int EleNr = 0;
int Status = 0;
//geheleRegel doormidden hakken voor x en y waardes.
String X = geheleRegel.SubString(0, (geheleRegel.Length() /2));
String Y = geheleRegel.SubString(geheleRegel.Length()/2 +1, geheleRegel.Length());
LinePiece lpObject(Code, EleNr, Status, StrToInt(X), StrToInt(Y));
LPArray[LPIndex] = lpObject;
LPIndex++;
Regel = "";
}
if(Code == "*" && firstElement == false) //Nieuw element
{
if(OrderNumber == "")
{
OrderNumber =="-";
}
if(OrderBrand == "")
{
OrderBrand = "-";
}
if(ElementNumber == "")
{
ElementNumber = "-";
}
if(ElementMarking == "")
{
ElementMarking = "-";
}
if (ReinforcementPattern == "")
{
ReinforcementPattern = "-";
}
if (CalculationNumber == "")
{
CalculationNumber = "-";
}
if(ElementLength == "")
{
ElementLength = 0;
}
if(ElementWidth == "")
{
ElementWidth = 0;
}
if(ElementBeginX == "")
{
ElementBeginX = 0;
}
if(ConcreteThickness == "")
{
ConcreteThickness = 0;
}
if(Isulation == "")
{
Isulation = 0;
}
if(Weight == "")
{
Weight = 0;
}
element ElementObject(OrderNumber, OrderBrand, ElementNumber, ElementMarking,
ReinforcementPattern, CalculationNumber, StrToInt(ElementLength), StrToInt(ElementWidth),
StrToInt(ElementBeginX), StrToInt(ConcreteThickness),StrToInt(Isulation),
Weight, LPArray);
ElementArray[Index] = ElementObject;
LPIndex = 0; /resetting LPIndex
Index++;
}
else
{
Regel="";
}
if (Code == "*")
{
firstElement = false;
}
}
}
}
return ElementArray;
}
So for some reason, it doesn't make 'X' different LPArrays, but overwrites all the LParrays with the last one. How can I fix this?
Your initialization code should looks like:
element *ElementArray = new element[100];
for ( int n = 0; n < 100; ++n )
ElementArray[n].arrayLP = new LinePiece[100];
so the behaviour you describe might be due to undefined bahaviour
you dont seem to delete your allocated array anywhere - that will cause memory leaks. Also if you want arrays and not vectors then you must obey rule of three (add copy constructor/operator and destructor).
I know that similar question has been asked,but I still can not figure out what is wrong.As mentioned above,I am debugging a program with VS2010 which always telling me "This may be due to a corruption of the heap, which indicates a bug in SwiftIndex.exe or any of the DLLs it has loaded...".So,here is part of my code:
Status PrefixQuickSI::my_QucikSI(std::vector<_QISymbol> &cur_sequence, QISequence graphcode, int depth, int feature_size, ECVector<char> cur_UsageTab, ECVector<SequenceIndex> cur_MappingTab, bool &flag)
{
Status st;
int vcnt = m_QueryGraph->V();
_QISymbol T;
if(depth == 0)
{
T.tSymbol = graphcode.sequence[depth]->tSymbol;
T.rSymbols.clear();
for(int i = 0; i < graphcode.sequence[depth]->numOfRSymbol; i++)
{
int v1,v2;
Label elabel;
v1 = graphcode.sequence[depth]->rSymbol[i].val;
v2 = graphcode.sequence[depth]->rSymbol[i+1].val;
elabel = graphcode.sequence[depth]->rSymbol[i].lable;
if(m_QueryGraph->getELabel(cur_MappingTab[v1],cur_MappingTab[v2]) != elabel)
{
flag = false;
return OK;
}
T.rSymbols.push_back(graphcode.sequence[depth]->rSymbol[i]);
T.rSymbols.push_back(graphcode.sequence[depth]->rSymbol[i+1]);
i++;
}
depth++;
cur_sequence.push_back(T);
if(depth == graphcode.numOfPrefixNode)
{
flag =true;
return OK;
}
else
{
st = my_QucikSI(cur_sequence, graphcode,depth, feature_size, cur_UsageTab, cur_MappingTab, flag);
if(flag == true)
{
return OK;
}
else
{
flag = false;
return OK;
}
}
}
else
{
T.tSymbol = graphcode.sequence[depth]->tSymbol;
for( int j = 0; j < graphcode.sequence[depth]->numOfRSymbol; ++j )
{
RSymbol rSymbol;
rSymbol = graphcode.sequence[depth]->rSymbol[j];
T.rSymbols.push_back(rSymbol);
}
int pV;
VertexIDSet Vcandiates;
for( int i = 0; i < vcnt; i++ )
{
pV = T.tSymbol.p;
if( cur_UsageTab[i] > 0 || m_QueryGraph->getLabel(i) != T.tSymbol.l || m_QueryGraph->getELabel(i, cur_MappingTab[pV]) != T.tSymbol.pl)
continue;
Vcandiates.insert(i);
}
for( VertexIDSet::const_iterator v = Vcandiates.begin(); v != Vcandiates.end(); v++ )
{
bool mis_match = false;
for( std::vector<RSymbol>::const_iterator r = T.rSymbols.begin(); r != T.rSymbols.end(); r++ )
{
if( !MatchREntry(cur_sequence, *v, *r) )
{
mis_match = true;
break;
}
}
if( mis_match )
continue;
cur_MappingTab[feature_size + depth] = *v;
cur_UsageTab[*v] = 1;
depth++;
cur_sequence.push_back(T);
if(depth == graphcode.numOfPrefixNode)
{
flag = true;
return OK;
}
else
{
st = my_QucikSI(cur_sequence, graphcode,depth, feature_size, cur_UsageTab, cur_MappingTab,flag);
if(flag == true)
{
return OK;
}
else
{
cur_UsageTab[*v] = 0;
depth--;
}
}
}
}
return OK;
}
and the calling function statement is:
int depth = 0;
st = my_QucikSI(cur_sequence, datacodes[cur_graphid], depth, cur_size,cur_UsageTab,cur_MappingTab, flag);
I have debugged step by step,and found that the "heap corruption" occurred in the second return of the recursion of function my_QuickSI(flag already equaled true at the third recursion and function returned to the second recursion,when it's about to return to the first recursion,the "heap corruption" happened).
Hope someone find where the problem is.
You can find my previous answer useful for your problem:
https://stackoverflow.com/a/22074401/2724703
In general heap corruption is often detected after the real corruption has already occurred by some DLL/module loaded within your process.