How can I plug this C++ memory leak? - c++

I have a program that is giving the expected output, however I am receiving the following errors below my output"
* glibc detected * PathFinder2: free(): invalid pointer: 0xb6046b70 ***
I run my program using Valgrind. However i do not have a file called pthread_create.c or pthread_create.c.
How can I troubleshoot the error based on these stats by Valgrind:
==3439== 800 bytes in 1 blocks are definitely lost in loss record 100 of
103
==3439== at 0x402ADFC: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3439== by 0x80560B5: Assignm3::Maze::InitMazeArray() (in /home/a/Desktop/PathFinder2)
==3439== by 0x8055167: Assignm3::Maze::LoadMaze(std::string) (in /home/a/Desktop/PathFinder2)
==3439== by 0x804A1F8: solveMaze(void*) (in /home/a/Desktop/PathFinder2)
==3439== by 0x4052F6F: start_thread (pthread_create.c:312)
==3439== by 0x42A170D: clone (clone.S:129)
Update
Is there logic error in this part which lead to memory leak. I cant seem to find anything wrong.
static void *solveMaze(void *vptr_args)
{
Point point1, point2, point3;
int nxtPx, nxtPy;
mazeObj->LoadMaze();
point1 = mazeObj->getStartLocation();
point3 = mazeObj->getEndLocation();
VectorOfPointStructType Path, vecMain;
Path.push_back(point1);
vecMain.push_back(point1);
point2 = mazeObj->getEndLocation();
nxtPx = point1.getX();
nxtPy = point1.getY();
sleep(3);
while (true)
{
string thread1, thread2;
thread1 = THREAD_NAMES[line1];
thread2 = THREAD_NAMES[line2];
cout << "Thread " << THREAD_NAMES[line1] << " is running" << endl;
cout << "Thread " << THREAD_NAMES[line2] << " is running" << endl;
for (int x = 0; x < 5; x++)
{
if (thread1 != THREAD_NAMES[line1] && thread2 != THREAD_NAMES[line2])
{
cout << "Thread " << THREAD_NAMES[line1] << " is running" << endl;
cout << "Thread " << THREAD_NAMES[line2] << " is running" << endl;
}
if (x == 0)
{
nxtPx++;
point3 = Point(nxtPx, nxtPy);
if ((mazeObj->IsThereBarrier(point3) || mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3, ob))
{
Path.push_back(point3);
vecMain.push_back(point3);
ob.push_back(point3);
if (mazeObj->IsThereBarrier(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToBarrier(pthread_self(), Path))
{
sleep(1);
}
pthread_mutex_unlock(&mutex1);
}
else if (mazeObj->IsThereDanger(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToDangerArea(pthread_self(), Path))
{
if (thread1 == THREAD_NAMES[line1])
{
diemsg1();
}
else if (thread2 == THREAD_NAMES[line2])
{
diemsg2();
}
create();
}
pthread_mutex_unlock(&mutex1);
}
nxtPx--;
Path.pop_back();
}
else if ((!mazeObj->IsThereBarrier(point3) && !mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3,
vecMain))
{
point1 = point3;
Path.push_back(point1);
vecMain.push_back(point1);
point3 = mazeObj->getEndLocation();
x = - 1;
if (point1.isConnected(point2) || reachEnd)
{
reachEnd = true;
break;
}
}
else
{
nxtPx--;
}
}
else if (x == 1)
{
nxtPy++;
point3 = Point(nxtPx, nxtPy);
if ((mazeObj->IsThereBarrier(point3) || mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3, ob))
{
Path.push_back(point3);
vecMain.push_back(point3);
ob.push_back(point3);
if (mazeObj->IsThereBarrier(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToBarrier(pthread_self(), Path))
{
sleep(1);
}
pthread_mutex_unlock(&mutex1);
}
else if (mazeObj->IsThereDanger(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToDangerArea(pthread_self(), Path))
{
if (thread1 == THREAD_NAMES[line1])
{
diemsg1();
}
else if (thread2 == THREAD_NAMES[line2])
{
diemsg2();
}
create();
}
pthread_mutex_unlock(&mutex1);
}
nxtPy--;
Path.pop_back();
}
else if ((!mazeObj->IsThereBarrier(point3) && !mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3,
vecMain))
{
point1 = point3;
Path.push_back(point1);
vecMain.push_back(point1);
point3 = mazeObj->getEndLocation();
x = - 1;
if (point1.isConnected(point2) || reachEnd)
{
reachEnd = true;
break;
}
}
else
{
nxtPy--;
}
}
else if (x == 2)
{
nxtPx--;
point3 = Point(nxtPx, nxtPy);
if ((mazeObj->IsThereBarrier(point3) || mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3, ob))
{
Path.push_back(point3);
vecMain.push_back(point3);
ob.push_back(point3);
if (mazeObj->IsThereBarrier(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToBarrier(pthread_self(), Path))
{
sleep(2);
}
pthread_mutex_unlock(&mutex1);
}
else if (mazeObj->IsThereDanger(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToDangerArea(pthread_self(), Path))
{
if (thread1 == THREAD_NAMES[line1])
{
diemsg1();
}
else if (thread2 == THREAD_NAMES[line2])
{
diemsg2();
}
create();
}
pthread_mutex_unlock(&mutex1);
}
nxtPx++;
Path.pop_back();
}
else if ((!mazeObj->IsThereBarrier(point3) && !mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3,
vecMain))
{
point1 = point3;
Path.push_back(point1);
vecMain.push_back(point1);
point3 = mazeObj->getEndLocation();
x = - 1;
if (point1.isConnected(point2) || reachEnd)
{
reachEnd = true;
break;
}
}
else
{
nxtPx++;
}
}
else if (x == 3)
{
nxtPy--;
point3 = Point(nxtPx, nxtPy);
if ((mazeObj->IsThereBarrier(point3) || mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3, ob))
{
Path.push_back(point3);
vecMain.push_back(point3);
ob.push_back(point3);
if (mazeObj->IsThereBarrier(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToBarrier(pthread_self(), Path))
{
sleep(2);
}
pthread_mutex_unlock(&mutex1);
}
else if (mazeObj->IsThereDanger(point3))
{
pthread_mutex_lock(&mutex1);
if (submitMazeSolnObj->submitPathToDangerArea(pthread_self(), Path))
{
if (thread1 == THREAD_NAMES[line1])
{
diemsg1();
}
else if (thread2 == THREAD_NAMES[line2])
{
diemsg2();
}
create();
}
pthread_mutex_unlock(&mutex1);
}
nxtPy++;
Path.pop_back();
}
else if ((!mazeObj->IsThereBarrier(point3) && !mazeObj->IsThereDanger(point3)) && !pathObj->isLocationInPath(point3,
vecMain))
{
point1 = point3;
Path.push_back(point1);
vecMain.push_back(point1);
point3 = mazeObj->getEndLocation();
x = - 1;
if (point1.isConnected(point2) || reachEnd)
{
reachEnd = true;
break;
}
}
else
{
nxtPy++;
}
}
else if (x == 4)
{
pthread_mutex_lock(&mutex1);
for (;;)
{
point1 = Path[Path.size() - 2];
nxtPx = point1.getX();
nxtPy = point1.getY();
point3 = Point(nxtPx - 1, nxtPy);
if (!pathObj->isLocationInPath(point3, vecMain))
{
x = 0;
Path.pop_back();
if (mazeObj->IsThereBarrier(point3))
{
point3 = mazeObj->getEndLocation();
}
pthread_mutex_unlock(&mutex1);
break;
}
point3 = Point(nxtPx, nxtPy + 1);
if (!pathObj->isLocationInPath(point3, vecMain))
{
x = - 1;
Path.pop_back();
if (mazeObj->IsThereBarrier(point3))
{
point3 = mazeObj->getEndLocation();
}
pthread_mutex_unlock(&mutex1);
break;
}
point3 = Point(nxtPx + 1, nxtPy);
if (!pathObj->isLocationInPath(point3, vecMain))
{
x = 2;
Path.pop_back();
if (mazeObj->IsThereBarrier(point3))
{
point3 = mazeObj->getEndLocation();
}
pthread_mutex_unlock(&mutex1);
break;
}
point3 = Point(nxtPx, nxtPy - 1);
if (!pathObj->isLocationInPath(point3, vecMain))
{
x = 1;
Path.pop_back();
if (mazeObj->IsThereBarrier(point3))
{
point3 = mazeObj->getEndLocation();
}
pthread_mutex_unlock(&mutex1);
break;
}
Path.pop_back();
}
pthread_mutex_unlock(&mutex1);
int deX = point1.getX();
int deY = point1.getY();
if (thread1 == THREAD_NAMES[line1])
{
time(&end);
cout << "Thread: " << THREAD_NAMES[line1] << " found the dead end at " << "[ " << deX << " , " << deY << " ]" << endl;
cout << "Time Elapsed: " << difftime(end, start) << " seconds" << endl;
}
else if (thread2 == THREAD_NAMES[line2])
{
time(&end);
cout << "Thread: " << THREAD_NAMES[line2] << " found the dead end at " << "[ " << deX << " , " << deY << " ]" << endl;
cout << "Time Elapsed: " << difftime(end, start) << " seconds" << endl;
}
}
else
{}
}
{
break;
}
}
Path.push_back(point2);
if (!submitPath)
{
submitMazeSolnObj->submitSolutionPath(pthread_self(), Path);
submitPath = true;
}
return NULL;
}

It seems that you have new[] without delete[] in Assignm3::Maze::InitMazeArray().

Related

How to make 2 functions work instead of only 1

I have 2 void functions and a main func.
But since first function has while(true) it works always and due to that second is not working. How to make it work all together at the same time?
void shoot()
{
*(DWORD*)(val.gameModule + offsets.ForceAttack, 5);
Sleep(5000);
*(DWORD*)(val.gameModule + offsets.ForceAttack, 4);
}
void bunny()
{
val.gameModule = (DWORD)GetModuleHandle("client_panorama.dll");
std::cout << (GetModuleHandle("client_panorama.dll")) << std::endl;;
val.localPlayer = *(DWORD*)(val.gameModule + offsets.lplayer);
while (true)
{
if (bunnyON == 1);
else
return;
val.flag = *(BYTE*)(val.localPlayer + offsets.flags);
if (isMoving())
if (GetAsyncKeyState(VK_SPACE) && val.flag & (1 << 0))
* (DWORD*)(val.gameModule + offsets.jump) = 6;
}
}
int main()
{
bunny();
shoot();
}
`
Try to do this, and check if this is what you need:
#include <thread>
void shoot()
{
*(DWORD*)(val.gameModule + offsets.ForceAttack, 5);
Sleep(5000);
*(DWORD*)(val.gameModule + offsets.ForceAttack, 4);
}
void bunny()
{
val.gameModule = (DWORD)GetModuleHandle("client_panorama.dll");
std::cout << (GetModuleHandle("client_panorama.dll")) << std::endl;;
val.localPlayer = *(DWORD*)(val.gameModule + offsets.lplayer);
while (true)
{
if (bunnyON == 1);
else
return;
val.flag = *(BYTE*)(val.localPlayer + offsets.flags);
if (isMoving())
if (GetAsyncKeyState(VK_SPACE) && val.flag & (1 << 0))
* (DWORD*)(val.gameModule + offsets.jump) = 6;
}
}
int main()
{
std::thread t1(bunny);
std::thread t2(shoot);
t1.join();
t2.join();
return 0;
}

Bug color with my console menu

I am trying to do a menu driven by the keyboard's arrows. For this, I change the background of the selected item, like this:
But once I go to the last item and go up again, this happens:
There is my code for the selected items:
void Print::Select(int pos, int realpos)
{
if (pos == realpos)
SetconsoleTextAttribute(handle, 112);
else
SetConsoleTextAttribute(handle, m_white);
}
The entire code:
#include <Windows.h>
#include <iostream>
#include <conio.h>
#include "Options.hpp"
#include <math.h>
#define left_arrow 75
#define right_arrow 77
#define down_arrow 80
#define up_arrow 72
#define page_up 73
#define page_down 81
Config g_options;
class Print
{
public:
void Infos();
void State(bool state);
void Select(int pos, int realpos);
void Loop();
void CheckInput();
int m_red = 0xC;
int m_green = 0xA;
int m_white = 0x7;
int m_selection_color = 70;
char m_input;
int m_min = 1;
int m_max = 0;
unsigned int m_selection_pos = 1;
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
}; extern Print g_print;
void Print::CheckInput()
{
m_input = _getch();
Sleep(30);
if (m_input == page_up && g_options.current_tab != g_options.tabs[3])
g_options.current_tab = g_options.tabs[rand() % 3];
else if (m_input == page_down && g_options.current_tab != g_options.tabs[0])
g_options.current_tab = g_options.tabs[rand() % 3];
if (m_input == up_arrow && m_selection_pos != m_min)
m_selection_pos -= 1;
else if (m_input == down_arrow && m_selection_pos != m_max)
m_selection_pos += 1;
else if (m_input == left_arrow || m_input == right_arrow)
{
if (g_options.current_tab == g_options.tabs[0])
{
switch (m_selection_pos)
{
case 1:
g_options.aim_enabled = !g_options.aim_enabled; break;
case 2:
g_options.aim_autoconfig = !g_options.aim_autoconfig; break;
case 3:
g_options.aim_rcs = !g_options.aim_rcs; break;
case 4:
if (m_input == right_arrow) { g_options.aim_smooth++; break; }
else if (m_input == left_arrow) { g_options.aim_smooth--; break; }
}
}
if (g_options.current_tab == g_options.tabs[1])
{
switch (m_selection_pos)
{
case 1:
g_options.esp_enabled = !g_options.esp_enabled; break;
case 2:
g_options.esp_ennemies = !g_options.esp_ennemies; break;
case 3:
g_options.esp_friends = !g_options.esp_friends; break;
}
}
if (g_options.current_tab == g_options.tabs[2])
{
switch (m_selection_pos)
{
case 1:
g_options.trigger_enabled = !g_options.trigger_enabled;
case 2:
g_options.triggerbot_ennemies = !g_options.esp_ennemies;
case 3:
g_options.trigger_team = g_options.trigger_team;
case 4:
if (m_input == left_arrow) { g_options.trigger_delay -= 1; break; }
else if (m_input == right_arrow) { g_options.trigger_delay += 1; break; }
}
}
if (g_options.current_tab == g_options.tabs[3])
g_options.noflash_enabled = !g_options.noflash_enabled;
}
}
void Print::Select(int pos, int realpos)
{
if (pos == realpos)
{
SetConsoleTextAttribute(handle, 112);
}
else if (pos != realpos)
SetConsoleTextAttribute(handle, m_white);
}
void Print::State(bool state)
{
if (state)
{
SetConsoleTextAttribute(handle, m_green);
printf("[ON]\n");
SetConsoleTextAttribute(handle, m_white);
}
else if (!state)
{
SetConsoleTextAttribute(handle, m_red);
printf("[OFF]\n");
SetConsoleTextAttribute(handle, m_white);
}
}
void Print::Infos()
{
system("cls");
std::cout << "========= " << g_options.current_tab << " =========" << std::endl << std::endl;
if (g_options.current_tab == g_options.tabs[0])
{
Select(1, m_selection_pos); std::cout << "Enabled: "; State(g_options.aim_enabled);
Select(2, m_selection_pos); std::cout << "Autoconfig: "; State(g_options.aim_autoconfig);
Select(3, m_selection_pos); std::cout << "Recoil control: "; State(g_options.aim_rcs);
Select(4, m_selection_pos); std::cout << "Smooth: " << g_options.aim_smooth;
}
else if (g_options.current_tab == g_options.tabs[1])
{
Select(1, m_selection_pos); std::cout << "Enabled: "; State(g_options.esp_enabled);
Select(2, m_selection_pos); std::cout << "Glow ennemy: "; State(g_options.esp_ennemies);
Select(3, m_selection_pos); std::cout << "Glow team: "; State(g_options.esp_friends);
}
else if (g_options.current_tab == g_options.tabs[2])
{
Select(1, m_selection_pos); std::cout << "Enabled: "; State(g_options.trigger_enabled);
Select(2, m_selection_pos); std::cout << "Shoot ennemy: "; State(g_options.triggerbot_ennemies);
Select(3, m_selection_pos); std::cout << "Shoot team: "; State(g_options.trigger_team);
Select(4, m_selection_pos); std::cout << "Delay: " << g_options.trigger_delay;
}
else if (g_options.current_tab == g_options.tabs[3])
{
Select(1, m_selection_pos); std::cout << "Noflash: "; State(g_options.noflash_enabled);
}
}
void Print::Loop()
{
while (true)
{
Infos();
if (g_options.current_tab == g_options.tabs[0] || g_options.current_tab == g_options.tabs[2])
m_max = 4;
else if (g_options.current_tab == g_options.tabs[1])
m_max = 3;
else if (g_options.current_tab == g_options.tabs[3])
m_max = 1;
CheckInput();
}
}
I just noticed that the bug occurs only with the smooth option

Getting a "vector subscript out of range" error when passing a vector into a function: c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to write a c++ program that assembles MIPS instructions. While debugging, it keeps throwing an error at line 74 of my main:
myassembler.add(lexed[i].labels[0], lexed[i].name, tokens, i);
my main is here:
#include <fstream>
#include <iostream>
#include <iomanip>
#include <memory>
#include <stdexcept>
#include <string>
#include <sstream>
#include <vector>
#include "exceptions.h"
#include "lexer.h"
#include "util.h"
#include "assembler.h"
std::string read_file(const std::string& name) {
std::ifstream file(name);
if (!file.is_open()) {
std::string error = "Could not open file: ";
error += name;
throw std::runtime_error(error);
}
std::stringstream stream;
stream << file.rdbuf();
return std::move(stream.str());
}
int main(int argc, char** argv) {
// Adjusting -- argv[0] is always filename.
--argc;
++argv;
if (argc == 0) {
std::cerr << "Need a file" << std::endl;
return 1;
}
assembler myassembler;
for (int i = 0; i < argc; ++i) {
std::string asmName(argv[i]);
if (!util::ends_with_subseq(asmName, std::string(".asm"))) {
std::cerr << "Need a valid file name (that ends in .asm)" << std::endl;
std::cerr << "(Bad name: " << asmName << ")" << std::endl;
return 1;
}
// 4 is len(".asm")
auto length = asmName.size() - string_length(".asm");
std::string baseName(asmName.begin(), asmName.begin() + length);
std::string objName = baseName + ".obj";
try {
auto text = read_file(asmName);
try {
auto lexed = lexer::analyze(text); // Parses the entire file and returns a vector of instructions
for (int i =0; i < (int)lexed.size(); i++){
if(lexed[i].labels.size() > 0) // Checking if there is a label in the current instruction
std::cout << "label = " << lexed[i].labels[0] << "\n"; // Prints the label
std::cout<< "instruction name = " << lexed[i].name<< "\n"; // Prints the name of instruction
std::cout << "tokens = ";
std::vector<lexer::token> tokens = lexed[i].args;
for(int j=0; j < (int)tokens.size(); j++){ // Prints all the tokens of this instruction like $t1, $t2, $t3
if (tokens[j].type == lexer::token::Integer)
std::cout << tokens[j].integer() << " ";
else
std::cout << tokens[j].string() << " ";
}
myassembler.add(lexed[i].labels[0], lexed[i].name, tokens, i);
myassembler.p();
std::cout << "\n\n\n";
}
} catch(const bad_asm& e) {
std::stringstream error;
error << "Cannot assemble the assembly code at line " << e.line;
throw std::runtime_error(error.str());
} catch(const bad_label& e) {
std::stringstream error;
error << "Undefined label " << e.what() << " at line " << e.line;
throw std::runtime_error(error.str());
}
} catch (const std::runtime_error& err) {
std::cout << err.what() << std::endl;
return 1;
}
}
/*getchar();*/
return 0;
}
assembler.h:
#include "lexer.h"
#include <fstream>
#include <vector>
#include <string>
struct symbol
{
std::string label = "";
int slinenum;
};
struct relocation
{
std::string instruct = "";
std::string label = "";
int rlinenum;
int rt = 0;
int rs = 0;
};
struct opcode
{
std::string instruct = "";
int opc = 0;
bool isloadstore = false;
int extType = 0;
bool isbranch = false;
};
struct function
{
std::string instruct = "";
int funct = 0;
bool isjr = false;
bool isshift = false;
};
struct regs
{
std::string name;
int num;
};
enum instrtype
{
R, I, neither
};
class assembler
{
public:
assembler();
void oinit(void);
void finit(void);
void rinit(void);
void printToFile(std::fstream &file);
void savesymb(std::string label, int line);
void saverel(std::string instr, std::string label, int line, int rt, int rs);
std::vector<int> formatr(std::string instr, lexer::token toke1, lexer::token toke2, lexer::token toke3, int line);
int formatr(std::string instr, lexer::token toke, int line);
std::vector<int> formati(std::string instr, lexer::token toke1, lexer::token toke2, lexer::token toke3, int line);
std::vector<int> formati(std::string instr, lexer::token toke1, lexer::token toke2, int line);
int findnum(std::string regname);
void add(std::string label, std::string instr, const std::vector<lexer::token> &tokens, int linen);
void secAdd(void);
int rassemble(std::string instr, int rd, int rs, int rt, int shamt);
int iassemble(std::string instr, int rt, int rs, int imm);
void p();
private:
std::vector<int> results;
std::vector<symbol> symbtable;
std::vector<relocation> reloctable;
std::vector<opcode> ops;
std::vector<function> functions;
std::vector<regs> registers;
instrtype type = neither;
};
and assembler.cpp:
// ECE 2500
// Project 1: myAssembler
// assembler.cpp
// Sheila Zhu
#include "lexer.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "assembler.h"
assembler::assembler()
{
oinit();
finit();
rinit();
}
void assembler::oinit()
{
opcode myop;
myop.instruct = "addi";
myop.opc = 8;
myop.extType = 1;
ops.push_back(myop);
// more of the same
}
void assembler::finit()
{
function myfunc;
myfunc.instruct = "add";
myfunc.funct = 32;
functions.push_back(myfunc);
// more of the same
}
void assembler::rinit()
{
regs myreg;
myreg.name = "$zero";
myreg.num = 0;
registers.push_back(myreg);
//more of the same
}
void assembler::printToFile(std::fstream &file)
{
for (int i = 0; i < (int)results.size(); i++)
file << results.at(i) << std::endl;
}
void assembler::savesymb(std::string label, int line)
{
symbol symb;
symb.label = label;
symb.slinenum = line * 4;
symbtable.push_back(symb);
}
void assembler::saverel(std::string instr, std::string label, int line, int rt, int rs)
{
relocation re;
re.instruct = instr;
re.label = label;
re.rlinenum = line;
re.rt = rt;
re.rs = rs;
}
int assembler::findnum(std::string regname)
{
for (int i = 0; i < (int)registers.size(); i++)
{
if (regname == registers.at(i).name)
return registers.at(i).num;
}
return -1;
}
std::vector<int> assembler::formatr(std::string instr, lexer::token toke1, lexer::token toke2, lexer::token toke3, int line)
{
int rd = 0, rs = 0, rt = 0, shamt = 0;
std::vector<int> x;
function currf;
for (int i = 0; i < (int)functions.size(); i++)
{
if (instr == functions.at(i).instruct)
currf = functions.at(i);
}
try
{
if (currf.isshift)
{
if (toke1.type == lexer::token::Integer)
throw 1;
else
{
rd = findnum(toke1.string());
if (rd == -1)
throw 2;
}
if (toke2.type == lexer::token::Integer)
throw 1;
else
{
rs = findnum(toke2.string());
if (rs == -1)
throw 2;
}
if (toke3.type == lexer::token::Integer)
{
shamt = toke3.integer();
if (shamt < 0)
throw 3;
}
else
throw 1;
}
else
{
if (toke1.type == lexer::token::Integer)
throw 1;
else
{
rd = findnum(toke1.string());
if (rd == -1)
throw 2;
}
if (toke2.type == lexer::token::Integer)
throw 1;
else
{
rs = findnum(toke2.string());
if (rs == -1)
throw 2;
}
if (toke3.type == lexer::token::Integer)
throw 1;
else
{
rt = findnum(toke3.string());
if (rt == -1)
throw 2;
}
}
}
catch (int e)
{
if (e == 1)
std::cerr << "Wrong argument in line " << line << std::endl;
else if (e == 2)
std::cerr << "Invalid register name in line " << line << std::endl;
else
std::cerr << "Shift amount cannot be negative in line " << line << std::endl;
}
x.push_back(rd);
x.push_back(rs);
x.push_back(rt);
x.push_back(shamt);
return x;
}
int assembler::formatr(std::string instr, lexer::token toke, int line)
{
int rs = 0;
try
{
if (toke.type == lexer::token::Integer)
throw 1;
else
{
rs = findnum(toke.string());
if (rs == -1)
throw 2;
}
}
catch (int e)
{
if (e == 1)
std::cerr << "Wrong argument in line " << line << std::endl;
else
std::cerr << "Invalid register name in line " << line << std::endl;
}
return rs;
}
std::vector<int> assembler::formati(std::string instr, lexer::token toke1, lexer::token toke2, lexer::token toke3, int line)
{
int rt = 0, rs = 0, imm = 0;
std::vector<int> x;
opcode currop;
for (int i = 0; i < (int)ops.size(); i++)
{
if (instr == ops.at(i).instruct)
currop = ops.at(i);
}
try
{
if (currop.isbranch)
{
if (toke1.type == lexer::token::Integer)
throw 1;
else
{
rt = findnum(toke1.string());
if (rt == -1)
throw 2;
}
if (toke2.type == lexer::token::Integer)
throw 1;
else
{
rs = findnum(toke2.string());
if (rs == -1)
throw 2;
}
if (toke3.type == lexer::token::Integer)
imm = toke3.integer();
else
saverel(instr, toke3.string(), line, rt, rs);
}
else if (currop.isloadstore)
{
if ((instr == "lbu") || (instr == "sb"))
{
if (toke2.type == lexer::token::String)
throw 1;
else
{
if (toke2.integer() < 0)
imm = (0xFFFF << 16) + (0xFF << 8) + toke2.integer();
else
imm = toke2.integer();
}
if (toke1.type == lexer::token::Integer)
throw 1;
else
{
rt = findnum(toke1.string());
if (rt == -1)
throw 2;
}
if (toke3.type == lexer::token::Integer)
throw 1;
else
{
rs = findnum(toke2.string());
if (rs == -1)
throw 2;
}
}
else
{
if (toke2.type == lexer::token::String)
throw 1;
else
{
if (toke2.integer() < 0)
imm = (0xFFFF << 16) + toke2.integer();
else
imm = toke2.integer();
}
if (toke1.type == lexer::token::Integer)
throw 1;
else
{
rt = findnum(toke1.string());
if (rt == -1)
throw 2;
}
if (toke3.type == lexer::token::Integer)
throw 1;
else
{
rs = findnum(toke2.string());
if (rs == -1)
throw 2;
}
}
}
else
{
if ((instr == "andi") || (instr == "ori"))
{
if (toke1.type == lexer::token::Integer)
throw 1;
else
{
rt = findnum(toke1.string());
if (rt == -1)
throw 2;
}
if (toke2.type == lexer::token::Integer)
throw 1;
else
{
rs = findnum(toke2.string());
if (rs == -1)
throw 2;
}
if (toke3.type == lexer::token::Integer)
imm = toke3.integer();
else
throw 1;
}
else
{
if (toke1.type == lexer::token::Integer)
throw 1;
else
{
rt = findnum(toke1.string());
if (rt == -1)
throw 2;
}
if (toke2.type == lexer::token::Integer)
throw 1;
else
{
rs = findnum(toke2.string());
if (rs == -1)
throw 2;
}
if (toke3.type == lexer::token::Integer)
{
if (toke3.integer() < 0)
imm = (0xFFFF << 16) + toke2.integer();
else
imm = toke3.integer();
}
else
throw 1;
}
}
}
catch (int e)
{
if (e == 1)
std::cerr << "Wrong argument in line " << line << std::endl;
else
std::cerr << "Invalid register name in line " << line << std::endl;
}
x.push_back(rt);
x.push_back(rs);
x.push_back(imm);
return x;
}
std::vector<int> assembler::formati(std::string instr, lexer::token toke1, lexer::token toke2, int line)
{
int rt = 0, imm = 0;
std::vector<int> rval;
try
{
if (toke1.type == lexer::token::Integer)
throw 1;
else
{
rt = findnum(toke1.string());
if (rt == -1)
throw 2;
}
if (toke2.type == lexer::token::String)
throw 1;
else
imm = toke2.integer();
}
catch (int e)
{
if (e == 1)
std::cerr << "Wrong argument in line " << line << std::endl;
else
std::cerr << "Invalid register name in line " << line << std::endl;
}
rval.push_back(rt);
rval.push_back(imm);
return rval;
}
void assembler::add(std::string label, std::string instr, const std::vector<lexer::token> &token, int linen)
{
int assembled = 0, rd = 0, rt = 0;
std::vector<int> argh;
int arg;
if (label.length() > 0)
savesymb(label, linen);
for (int i = 0; i < (int)functions.size(); i++)
{
if (instr == functions.at(i).instruct)
type = R;
}
for (int i = 0; i < (int)ops.size(); i++)
{
if (instr == ops.at(i).instruct)
type = I;
}
if (type == R)
{
try
{
if (instr == "jr")
{
if ((int)token.size() == 1)
{
arg = formatr(instr, token.at(0), linen);
assembled = rassemble(instr, rd, arg, rt, 0);
}
else
throw 1;
}
else
{
if ((int)token.size() == 3)
{
argh = formatr(instr, token.at(0), token.at(2), token.at(3), linen);
assembled = rassemble(instr, argh[0], argh[1], argh[2], argh[3]);
}
else
throw 1;
}
}
catch (int e)
{
if (e == 1)
std::cerr << "Wrong number of arguments at line " << linen << std::endl;
}
}
else if (type == I)
{
try
{
if (instr == "lui")
{
if ((int)token.size() == 2)
{
argh = formati(instr, token.at(0), token.at(1), linen);
assembled = iassemble(instr, argh[0], 0, argh[1]);
}
else
throw 1;
}
else
{
if ((int)token.size() == 3)
{
argh = formati(instr, token.at(0), token.at(1), token.at(2), linen);
assembled = iassemble(instr, argh[0], argh[1], argh[2]);
}
else
throw 1;
}
}
catch (int e)
{
if (e == 1)
std::cout << "Wrong number of arguments at line " << linen << std::endl;
}
}
else
std::cerr << "Instruction not recognized at line " << linen << std::endl;
results.push_back(assembled);
}
void assembler::secAdd(void)
{
std::vector<int>::iterator iter = results.begin();
for (int i = 0; i < (int)reloctable.size(); i++)
{
for (unsigned int j = 0; j < symbtable.size(); j++)
{
if (reloctable.at(i).label == symbtable.at(j).label)
{
int assembled = 0;
iter += (reloctable.at(i).rlinenum / 4);
for (unsigned int k = 0; k < ops.size(); k++)
{
if (reloctable.at(i).instruct == ops.at(k).instruct)
type = I;
}
if (type == I)
assembled = iassemble(reloctable.at(i).instruct, reloctable.at(i).rt, reloctable.at(i).rs, symbtable.at(i).slinenum);
else
std::cerr << "Instruction not recognized at line " << reloctable.at(i).rlinenum << std::endl;
results.erase(iter);
results.insert(iter, assembled);
}
}
}
}
int assembler::rassemble(std::string instr, int rd, int rs, int rt, int shamt)
{
int func = 0;
int code = 0;
for (int i = 0; i < (int)functions.size(); i++)
{
if (instr == functions.at(i).instruct)
{
func = functions.at(i).funct;
break;
}
else
{
if (i == (functions.size() - 1))
return -1;
}
}
code = (rs << 21) + (rt << 16) + (rd << 11) + (shamt << 6) + func;
return code;
}
int assembler::iassemble(std::string instr, int rt, int rs, int imm)
{
int op = 0;
int code = 0;
for (int i = 0; i < (int)ops.size(); i++)
{
if (instr == ops.at(i).instruct)
{
op = ops.at(i).opc;
break;
}
else
{
if (i == (ops.size() - 1))
return -1;
}
}
code = (op << 26) + (rs << 21) + (rt << 16) + imm;
return code;
}
void assembler::p()
{
for (int i = 0; i < (int)results.size(); i++)
std::cout << results.at(i) << " ";
std::cout << std::endl;
}
When debugging, the tokens parameter triggers the error, and the this pointer in the vector code shows that the vector size changes to 0 at these lines:
#if _ITERATOR_DEBUG_LEVEL == 2
if (size() <= _Pos)
What exactly is happening?
Sorry if my formatting is bad/wrong, etc., and please let me know if I should make any edits/provide more code.
Thanks in advance.
The error is caused by accessing by index vector element that does not exist.
In you case lexed[i] should be valid. So, the only possible issue may be with empty labels vector. Validate this vector before accessing its elements, for example
myassembler.add(lexed[i].labels.empty() ? "" : lexed[i].labels[0],
lexed[i].name, tokens, i);
Actually there is one more bug for very large lexed arrays when integer index may overflow. You should not cast result of .size() to int. Instead proper type should be used for i:
for (size_t i = 0; i < lexed.size(); i++)

C++ LNK Error 2019

rmap_utils.h
#ifndef UTILS_RANGE_MAP_H
#define UTILS_RANGE_MAP_H
#include <stdlib.h>
#include <string>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <fstream>
#include <iostream>
#include "opencv2\opencv.hpp"
class rmap_utils
{
public:
rmap_utils::rmap_utils(){}
rmap_utils::~rmap_utils(){}
int loadRmap(const std::string &path, float *& xMap, float *& yMap, float *& zMap, unsigned char *&rgbMap, int &height, int &width);
cv::Mat visualize_depth_image(float *img, int width, int height, bool visualize, std::string wName = "rangeMap");
cv::Mat visualize_rgb_image(unsigned char *img, int width, int height, bool visualize, std::string wName = "rangeMap");
cv::Mat visualize_normalized_rgb_image(float *img, int width, int height, bool visualize, std::string wName = "rangeMap");
float compute_rangeMap_resolution(float *xMap, float *yMap, float *zMap, int width, int height);
};
#endif
rmap_utils.cpp
#include "rmap_utils.h"
void Tokenize(const std::string &line, std::vector<std::string> &tokens, const std::string &delimiters = " ", const bool skipEmptyCells = true, const int maxNumTokens = std::numeric_limits<int>::max())
{
tokens.clear();
int nTokens = 0;
std::string::size_type pos = 0;
std::string::size_type lastPos = 0;
if(skipEmptyCells)
{
// Skip delimiters at beginning.
lastPos = line.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
pos = line.find_first_of(delimiters, lastPos);
while ( (std::string::npos != pos || std::string::npos != lastPos) && (nTokens < maxNumTokens) )
{
// Found a token, add it to the vector.
tokens.push_back(line.substr(lastPos, pos - lastPos));
nTokens++;
// Skip delimiters
lastPos = line.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = line.find_first_of(delimiters, lastPos);
}
}
else
{
while ( (std::string::npos != pos) && (nTokens < maxNumTokens) )
{
pos = line.find_first_of(delimiters, lastPos);
tokens.push_back(line.substr(lastPos, pos - lastPos));
nTokens++;
lastPos = pos+1;
}
}
}
template <typename T> void Read_Array(std::ifstream &filev, T* &aData, unsigned long int &nData, const bool binaryFile = true)
{
if (!filev.is_open() )
{
std::cout << "ERROR (Read_Array): file is not open";
getchar();
exit(-1);
}
if(binaryFile)
{
//read number of elements
filev.read((char*)&nData, sizeof(nData) );
aData = new T[nData];
//read data
filev.read((char*)aData, sizeof(T)*nData );
if(filev.gcount() != (sizeof(T)*nData) )
{
std::cout << "ERROR (Read_Array): filev.gcount() != (sizeof(T)*nData) " << filev.gcount() << " " << (sizeof(T)*nData) << std::endl;
std::cout << "Are you sure you opened the file in binary mode?";
getchar();
exit(-1);
}
if(!filev.good())
{
std::cout << "ERROR (Read_Array): !filev.good() [eof fail bad] [" << filev.eof() << " " << filev.fail() << " " << filev.bad() << "]" << std::endl;
std::cout << "Are you sure you opened the file in binary mode?";
getchar();
exit(-1);
}
}
else
{
//read number of elements
std::string line;
std::getline(filev, line);
filev >> nData;
aData = new T[nData];
//read data
T* ptrData = aData;
for(unsigned long int da=0; da<nData; da++)
{
filev >> *ptrData;
ptrData++;
}
std::getline(filev, line);
if(!filev.good())
{
std::cout << "ERROR (Read_Array): !filev.good() [eof fail bad] [" << filev.eof() << " " << filev.fail() << " " << filev.bad() << "]" << std::endl;
getchar();
exit(-1);
}
}
}
template <typename T> void Read_Vector(std::ifstream &filev, std::vector<T> &vData, const bool binaryFile = true)
{
if (!filev.is_open() )
{
std::cout << "ERROR (Read_Vector): file is not open";
getchar();
exit(-1);
}
unsigned long int nData = 0;
if(binaryFile)
{
//read number of elements
filev.read((char*)&nData, sizeof(nData) );
vData.resize((size_t)nData);
//read data
filev.read((char*)(&vData[0]), sizeof(T)*nData );
if(filev.gcount() != (sizeof(T)*nData) )
{
std::cout << "ERROR (Read_Vector): filev.gcount() != (sizeof(T)*nData) " << filev.gcount() << " " << (sizeof(T)*nData) << std::endl;
std::cout << "Are you sure you opened the file in binary mode?";
getchar();
exit(-1);
}
if(!filev.good())
{
std::cout << "ERROR (Read_Vector): !filev.good() [eof fail bad] [" << filev.eof() << " " << filev.fail() << " " << filev.bad() << "]" << std::endl;
std::cout << "Are you sure you opened the file in binary mode?";
getchar();
exit(-1);
}
}
else
{
//read number of elements
std::string line;
std::getline(filev, line);
filev >> nData;
vData.resize((size_t)nData);
//read data
T* ptrData = &vData[0];
for(unsigned long int da=0; da<nData; da++)
{
filev >> (*ptrData);
ptrData++;
}
std::getline(filev, line);
if(!filev.good())
{
std::cout << "ERROR (Read_Vector): !filev.good() [eof fail bad] [" << filev.eof() << " " << filev.fail() << " " << filev.bad() << "]" << std::endl;
getchar();
exit(-1);
}
}
}
template<typename T> T LexicalCast(const std::string& s)
{
std::stringstream ss(s);
T result;
if ((ss >> result).fail() || !(ss >> std::ws).eof())
{
//throw std::bad_cast();
std::cout << "ERROR:Impossible to cast " << s;
getchar();
exit(-1);
}
return result;
}
//passi i puntatori vuoti e lui elaborando li riempe per come ti servono
int loadRmap(const std::string &path, float *& xMap, float *& yMap, float *& zMap, unsigned char *&rgbMap, int &height, int &width)
{
bool binaryFile = true;
std::ifstream in(path.c_str(), std::ios::binary|std::ios::in);
if(!in.is_open())
{
std::cout << "ERROR (RangeMap::Load_RMap): Problems opening file";
getchar();
exit(-1);
}
std::string line;
std::vector<std::string> tokens;
int nValidPoints = 0;
bool texture = false;
int nChannels = 1;
double resolution;
//read header
while (!in.eof())
{
getline (in, line);
// Ignore empty lines
if (line == "")
continue;
// Tokenize the line
Tokenize(line, tokens, "\t\r " );
// first line
if (tokens[0] == "RMap")
continue;
// version
if (tokens[0] == "version")
{
continue;
}
// height
if (tokens[0] == "height")
{
height = LexicalCast<int>(tokens[1]);
continue;
}
// width
if (tokens[0] == "width")
{
width = LexicalCast<int>(tokens[1]);
continue;
}
// nValidPoints
if (tokens[0] == "nValidPoints")
{
nValidPoints = LexicalCast<int>(tokens[1]);
continue;
}
// resolution
if (tokens[0] == "resolution")
{
resolution = LexicalCast<double>(tokens[1]);
continue;
}
// texture
if (tokens[0] == "texture")
{
texture = true;
if (tokens[1] == "GrayScale")
{
nChannels = 1;
}
else if (tokens[1] == "BGR")
{
nChannels = 3;
}
else
{
std::cout << "ERROR (RangeMap::Load_RMap): tokens[1] != \"GrayScale\" and tokens[1] != \"BGR\" ";
getchar();
exit(-1);
}
continue;
}
// end_header
if (tokens[0] == "headerEnd")
{
break;
}
}
if(in.eof())
{
in.close();
std::cout << "ERROR (RangeMap::Load_RMap): end_header tag not reached";
getchar();
exit(-1);
}
//read valid point map
bool* validMap = NULL;
unsigned long int nTotalPoints = 0;
Read_Array(in, validMap, nTotalPoints, binaryFile);
if(nTotalPoints != width*height)
{
in.close();
std::cout << "ERROR (RangeMap::Load_RMap): nTotalPoints != m_width*m_height " << nTotalPoints << " != " << width << " * " << height << std::endl;
getchar();
exit(-1);
}
//read maps
std::vector<float> xVals;
std::vector<float> yVals;
std::vector<float> zVals;
Read_Vector(in, xVals, binaryFile);
Read_Vector(in, yVals, binaryFile);
Read_Vector(in, zVals, binaryFile);
if(xVals.size() != nValidPoints)
{
in.close();
std::cout << "ERROR (RangeMap::Load_RMap): vMap_X.size() != nValidPoints " << xVals.size() << " != " << nValidPoints << std::endl;
getchar();
exit(-1);
}
if(yVals.size() != nValidPoints)
{
in.close();
std::cout << "ERROR (RangeMap::Load_RMap): vMap_Y.size() != nValidPoints " << yVals.size() << " != " << nValidPoints << std::endl;
getchar();
exit(-1);
}
if(zVals.size() != nValidPoints)
{
in.close();
std::cout << "ERROR (RangeMap::Load_RMap): vMap_Z.size() != nValidPoints " << zVals.size() << " != " << nValidPoints << std::endl;
getchar();
exit(-1);
}
//if(xMap)
//{
// delete[] xMap;
//}
xMap = new float[width*height];
/*if(yVals)
{
delete[] yVals;
}*/
yMap = new float[width*height];
/*if(zVals)
{
delete[] zVals;
}*/
zMap = new float[width*height];
float* ptrvMap_X = &xVals[0];
float* ptrvMap_Y = &yVals[0];
float* ptrvMap_Z = &zVals[0];
bool* ptrValidMap = validMap;
float* ptrXmap = xMap;
float* ptrYmap = yMap;
float* ptrZmap = zMap;
for(unsigned long int po=0; po<nTotalPoints; po++)
{
if(*ptrValidMap)
{
*ptrXmap = *(ptrvMap_X++);
*ptrYmap = *(ptrvMap_Y++);
*ptrZmap = *(ptrvMap_Z++);
}
else
{
*ptrZmap = std::numeric_limits<float>::quiet_NaN();
}
ptrXmap++;
ptrYmap++;
ptrZmap++;
ptrValidMap++;
}
delete[] validMap;
//read texture
if(texture)
{
IplImage* m_texture = cvCreateImage(cvSize(width, height), 8, nChannels);
rgbMap = new unsigned char[width*height*3];
in.read( (char*)(m_texture->imageData), height*m_texture->widthStep );
if(in.gcount() != height*m_texture->widthStep)
{
std::cout << "ERROR (RangeMap::Load_RMap): in.gcount() != m_height*m_texture->widthStep " << in.gcount() << " " << height*m_texture->widthStep;
getchar();
exit(-1);
}
if(!in.good())
{
std::cout << "ERROR (RangeMap::Load_RMap): !in.good() in reading m_texture [eof fail bad] [" << in.eof() << " " << in.fail() << " " << in.bad() << "]";
getchar();
exit(-1);
}
for (int j=0; j<height; j++)
{
for ( int i=0; i<width; i++)
{
if ( nChannels == 3)
{
rgbMap[ j*width*3+i*3 ] = ((unsigned char *)(m_texture->imageData))[ j * m_texture->widthStep + i*3];
rgbMap[ j*width*3+i*3 +1 ] = ((unsigned char *)(m_texture->imageData))[ j * m_texture->widthStep + i*3 +1];
rgbMap[ j*width*3+i*3 +2 ] = ((unsigned char *)(m_texture->imageData))[ j * m_texture->widthStep + i*3 +2];
}
else
{
rgbMap[ j*width*3+i*3+2 ] = ((unsigned char *)(m_texture->imageData))[ j * m_texture->widthStep + i];
rgbMap[ j*width*3+i*3+1 ] = ((unsigned char *)(m_texture->imageData))[ j * m_texture->widthStep + i];
rgbMap[ j*width*3+i*3 ] = ((unsigned char *)(m_texture->imageData))[ j * m_texture->widthStep + i];
}
}
}
/*cvNamedWindow("cicciux", 0);
cvShowImage("cicciux", m_texture);
cvWaitKey(0);*/
cvReleaseImage(&m_texture);
}
else
{
rgbMap = NULL;
}
in.close();
return nValidPoints;
}
cv::Mat visualize_depth_image(float *img, int width, int height, bool visualize, std::string wName)
{
cv::Mat mat(height, width, CV_8UC3);
float dmax = -1;
float dmin = std::numeric_limits<float>::max();
for ( int j=0; j<height; j++)
{
for ( int i=0; i<width; i++)
{
if ( img[j*width+i] == img[j*width+i] )
{
if ( img[j*width+i] > dmax )
dmax = img[j*width+i];
if (img[j*width+i]<dmin)
dmin = img[j*width+i];
}
}
}
for ( int j=0; j<height; j++)
{
for ( int i=0; i<width; i++)
{
if ( img[j*width+i] == img[j*width+i] )
{
unsigned char pixel = cv::saturate_cast<unsigned char>( ((img[j*width+i] - dmin)* 255.0f) / (dmax-dmin) ) ;
mat.at<cv::Vec3b>(j,i)[0] = pixel;
mat.at<cv::Vec3b>(j,i)[1] = pixel;
mat.at<cv::Vec3b>(j,i)[2] = pixel;
}
else
{
mat.at<cv::Vec3b>(j,i)[0] = 0;
mat.at<cv::Vec3b>(j,i)[1] = 0;
mat.at<cv::Vec3b>(j,i)[2] = 255;
}
}
}
if ( visualize)
{
cv::imshow(wName, mat);
cv::waitKey(0);
}
return mat;
}
cv::Mat visualize_rgb_image(unsigned char *img, int width, int height, bool visualize, std::string wName)
{
cv::Mat mat(height, width, CV_8UC3);
for ( int j=0; j<height; j++)
{
for ( int i=0; i<width; i++)
{
for ( int c=0; c<3; c++)
{
mat.at<cv::Vec3b>(j,i)[c] = img[j*width*3 + i*3 + c];
}
}
}
if ( visualize )
{
cv::imshow(wName, mat);
cv::waitKey(0);
}
return mat;
}
cv::Mat visualize_normalized_rgb_image(float *img, int width, int height, bool visualize, std::string wName)
{
cv::Mat mat(height, width, CV_8UC3);
for ( int j=0; j<height; j++)
{
for ( int i=0; i<width; i++)
{
for ( int c=0; c<3; c++)
{
mat.at<cv::Vec3b>(j,i)[c] = static_cast<unsigned char>(std::floor(img[j*width*3 + i*3 + c] * 255));
}
}
}
if ( visualize)
{
cv::imshow(wName, mat);
cv::waitKey(0);
}
return mat;
}
float compute_rangeMap_resolution(float *xMap, float *yMap, float *zMap, int width, int height)
{
float res = 0.0f;
int nCount = 0;
for ( int j=0; j<height-1; j++)
{
for ( int i=0; i<width-1; i++)
{
if ( zMap[j*width+i] == zMap[j*width+i] )
{
if ( zMap[j*width+i+1] == zMap[j*width+i+1] )
{
nCount ++ ;
res += (zMap[j*width+i]-zMap[j*width+i+1])*(zMap[j*width+i]-zMap[j*width+i+1]) + (yMap[j*width+i]-yMap[j*width+i+1])*(yMap[j*width+i]-yMap[j*width+i+1]) + (xMap[j*width+i]-xMap[j*width+i+1])*(xMap[j*width+i]-xMap[j*width+i+1]);
}
if ( zMap[(j+1)*width+i] == zMap[(j+1)*width+i] )
{
nCount ++ ;
res += (zMap[j*width+i]-zMap[(j+1)*width+i])*(zMap[j*width+i]-zMap[(j+1)*width+i]) + (yMap[j*width+i]-yMap[(j+1)*width+i])*(yMap[j*width+i]-yMap[(j+1)*width+i]) + (xMap[j*width+i]-xMap[(j+1)*width+i])*(xMap[j*width+i]-xMap[(j+1)*width+i]);
}
}
}
}
res /= nCount;
res = sqrt(res);
return res;
}
Error List:
error LNK2019: unresolved external symbol "public: int __cdecl rmap_utils::loadRmap(class std::basic_string,class std::allocator > const &,float * &,float * &,float * &,unsigned char * &,int &,int &)" (?loadRmap#rmap_utils##QEAAHAEBV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##AEAPEAM11AEAPEAEAEAH3#Z) referenced in function main
In rmap_utils.cpp replace
int loadRmap(const std::string &path, float *& xMap, float *& yMap, float *& zMap, unsigned char *&rgbMap, int &height, int &width)
With:
int rmap_utils::loadRmap(const std::string &path, float *& xMap, float *& yMap, float *& zMap, unsigned char *&rgbMap, int &height, int &width)

SDLNet: How to define the server IP address

I already succeeded when trying to connect a client to a server. But the server was using the loopback ip address. How is it possible to make a server using SDLNet so that i can access it from any computer that is connected to any network?
The problem is the code because I don't find any place where I can define another IP address for the server...
Here is the code for the server:
#include "Link\SDL\include\SDL.h"
#include "Link\SDL\include\SDL_net.h"
#include <iostream>
#include <vector>
int main(int argc, char *argv[])
{
SDL_Init(SDL_INIT_EVERYTHING);
SDLNet_Init();
int curid=2;
int playernum = 0;
char data[1400];
bool running=true;
SDL_Event event;
IPaddress ip;
SDLNet_ResolveHost(&ip,NULL,1234);
SDLNet_SocketSet sockets=SDLNet_AllocSocketSet(30); //max player
std::vector<TCPsocket> socketsvector;
TCPsocket server=SDLNet_TCP_Open(&ip);
while(running)
{
while(SDL_PollEvent(&event))
{
if(event.type==SDL_QUIT || event.type==SDL_KEYDOWN && event.key.keysym.sym==SDLK_ESCAPE)
{
running=false;
break;
}
}
TCPsocket tmpsocket=SDLNet_TCP_Accept(server);
if(tmpsocket)
{
if(playernum<30)
{
SDLNet_TCP_AddSocket(sockets,tmpsocket);
socketsvector.push_back(tmpsocket);
sprintf(data,"0 %d \n",curid);
curid++;
playernum++;
std::cout << "new connection. ID: " << curid << std::endl;
}
else
{
sprintf(data,"3 \n"); //server is full
}
SDLNet_TCP_Send(tmpsocket,data,strlen(data)+1);
}
while(SDLNet_CheckSockets(sockets,0) > 0)
{
for(int i=0;i<socketsvector.size();i++)
{
if(SDLNet_SocketReady(socketsvector[i])==1)
{
SDLNet_TCP_Recv(socketsvector[i],data,1400);
int num=data[0]-'0';
int j=1;
while(data[j]>='0' && data[j]<='9')
{
num*=10;
num+=data[j]-'0';
j++;
}
if(num==1)
{
for(int k=0;k<socketsvector.size();k++)
{
if(k==i)
continue;
SDLNet_TCP_Send(socketsvector[k],data,strlen(data)+1);
}
}else if(num==2)
{
for(int k=0;k<socketsvector.size();k++)
{
if(k==i)
continue;
SDLNet_TCP_Send(socketsvector[k],data,strlen(data)+1);
}
SDLNet_TCP_DelSocket(sockets,socketsvector[i]);
SDLNet_TCP_Close(socketsvector[i]);
socketsvector.erase(socketsvector.begin()+i);
playernum--;
std::cout << "connection closed..." << std::endl;
std::cout << playernum << " players in server" << std::endl;
}
}
}
}
//SDL_Delay(30);
}
SDLNet_TCP_Close(server);
SDLNet_FreeSocketSet(sockets);
SDLNet_Quit();
SDL_Quit();
return 0;
}
Ok, and here is the code for the client...
class network{
private:
SDLNet_SocketSet sockets;
TCPsocket connection;
char data[1400];
public:
network(const char* ip);
~network();
void send(Player* p);
void receive(std::vector<Enemy*>& enemies, Player* p); //std::vector<unsigned int>& f,std::vector<enemy*>& enemies,std::vector<weapon*> weapons,player* p
void closeConnection();
};
network::network(const char* ipaddress)
{
SDLNet_Init();
IPaddress ip;
if(SDLNet_ResolveHost(&ip,ipaddress,1234)==-1)
std::cout << "error while resolving the host (bad ip?)" << std::endl;
connection=SDLNet_TCP_Open(&ip);
sockets=SDLNet_AllocSocketSet(1);
if(sockets==NULL)
std::cout << "error while connecting (bad ip?)" << std::endl;
SDLNet_TCP_AddSocket(sockets,connection);
}
void network::closeConnection()
{
SDLNet_TCP_Send(connection,"2 \n",4); //close with the server
}
network::~network()
{
SDLNet_TCP_Close(connection);
SDLNet_FreeSocketSet(sockets);
SDLNet_Quit();
}
void network::send(Player* p)
{
vector3d vec=p->cam.getVector();
//1 curframe position rotation lookdirection health curweaponnum
sprintf(data,"1 %d %f %f %f %f %f %f \n",p->id, p->cam.getLocation().x,p->cam.getLocation().y,p->cam.getLocation().z,vec.x,vec.y,vec.z);
int size=0;
int len=strlen(data)+1;
//SDLNet_TCP_Send(connection,data,len);
while(size<len)
{
size+=SDLNet_TCP_Send(connection,data+size,len-size);
}
}
void network::receive(std::vector<Enemy*>& enemies, Player* p) //std::vector<unsigned int>& f,std::vector<enemy*>& enemies,std::vector<weapon*> weapons,player* p
{
SDLNet_CheckSockets(sockets,10);
if(SDLNet_SocketReady(connection))
{
int tmp,num;
int offset=0;
do
{
offset=SDLNet_TCP_Recv(connection,(char*)data+(offset),1400);
if(offset<=0)
return;
}while(data[strlen(data)-1]!='\n');
sscanf(data,"%d %d",&num,&tmp);
//cout << num << " " << tmp << endl;
cout << data << endl;
int i=0;
if(num == 0)
{
p->setId(tmp);
}
else if(num==1)
{
bool NewEnemy = true;
for(i=0;i<enemies.size();i++)
{
if(enemies[i]->id == tmp)
{
int nothing;
sscanf(data,"1 %d %f %f %f %f %f %f \n",&nothing, &(enemies[i]->position.x),&(enemies[i]->position.y),&(enemies[i]->position.z),&(enemies[i]->rotation.x),&(enemies[i]->rotation.y),&(enemies[i]->rotation.z));
NewEnemy = false;
break;
}
}
if(NewEnemy == true && tmp != 0)
{
std::cout << "pusing new enemy" << std::endl;
enemies.push_back(new Enemy(tmp));
}
}
else if(num == 2)
{
for(int k = 0; k < enemies.size(); k++)
{
if(enemies[k]->id == tmp)
{
enemies.erase(enemies.begin() + k);
}
}
}
else if(num == 3)
{
std::cout << "Could not connect. Server is full." << std::endl;
}
}
}
If you can see, I type the IP address for the client when the program starts. But the only value that works is the loopback address.