I have below class
class Cdata12Mnt
{
public:
char IOBname[ID1_IOB_PIOTSUP-ID1_IOB_TOP][BOADNAM_MAX + 4];
char ExIOBname[ID1_MAX_INF-ID1_EXIOB_U1TOP][BOADNAM_MAX + 4];
char cflpath[256];
char basetext[256];
UINT database[ID1_MAX_INF];
int State;
public:
char SelectPath[256];
public:
int GetIOBName(int slt,char *Name);
Cdata12Mnt(char *SelectPath);
virtual ~Cdata12Mnt();
int GetValue(int id);
int GetState() { return State; }
};
And I have function as below
Cdata12Mnt::Cdata12Mnt(char *SelectPath)
{
SCTReg reg;
char buf[256], *cpnt, *npnt, *bpnt1, *bpnt2;
char *startcode[] = {"CNTL_CODE ","SEGMENT "};
char *stopcode = {"END_CNTL_CODE "};
FILE *fp;
int ii, infl;
State = 0;
for (ii = 0; ii < (ID1_IOB_PIOTSUP - ID1_IOB_TOP); ii++) {
strcpy(IOBname[ii], "");
}
for (ii = 0; ii < (ID1_MAX_INF-ID1_EXIOB_U1TOP); ii++) {
**strcpy(ExIOBname[ii], "");**
}
sprintf(cflpath, "%s\\%s", SelectPath, CDATAFL);
if ((fp = fopen(cflpath,"r"))!=NULL) {
for (ii = 0, infl = 0; fgets(buf, 256, fp) != NULL;) {
if (infl == 0 && strncmp(buf, startcode[0], strlen(startcode[0])) == 0) {
if ((cpnt = strchr(&buf[strlen(startcode[0])],*startcode[1])) != NULL) {
if (strncmp(cpnt,startcode[1], strlen(startcode[1])) == 0) {
infl = 1;
continue;
}
}
}
if (infl == 0) {
continue;
}
if (strncmp(buf,stopcode,strlen(stopcode))==0) {
if (ii == ID1_EXIOB_U1TOP) {
for (int nDataNumber = ii; nDataNumber < ID1_MAX_INF; nDataNumber++) {
database[nDataNumber] = 0;
}
}
infl = 0;
continue;
}
if (strncmp(&buf[14], " DD ", 4) == 0) {
if ((cpnt=strchr(buf, ';')) != NULL) {
*cpnt = '\0';
}
if (ii >= ID1_IOB_TOP && ii < ID1_IOB_PIOTSUP) {
if ((bpnt1 = strchr(cpnt + 1,'(')) != NULL && (bpnt2=strchr(cpnt + 1,')'))!=NULL && bpnt1 < bpnt2) {
*bpnt2 = '\0';
*(bpnt1 + BOADNAM_MAX + 1) = '\0';
strcpy(IOBname[ii-ID1_IOB_TOP], bpnt1 + 1);
}
}
if (ii >= ID1_EXIOB_U1TOP && ii < ID1_MAX_INF) {
if ((bpnt1 = strchr(cpnt + 1, '(')) != NULL && (bpnt2=strchr(cpnt+1,')'))!=NULL && bpnt1 < bpnt2) {
*bpnt2='\0';
*(bpnt1+BOADNAM_MAX+1)='\0';
strcpy(ExIOBname[ii-ID1_EXIOB_U1TOP], bpnt1 + 1);
}
}
for (cpnt = &buf[18]; cpnt != NULL;) {
if ((npnt=strchr(cpnt, ',')) != NULL)
*npnt='\0';
}
if (strchr(cpnt,'H')!=NULL) {
sscanf(cpnt,"%XH",&database[ii]);
} else {
database[ii]=atoi(cpnt);
}
ii++;
cpnt = npnt;
if (cpnt != NULL) {
cpnt++;
}
}
}
}
fclose(fp);
} else {
State=-1;
}
When I compile this function in Visual studio 2008, it gives me error at strcpy(IOBname[ii],""); as below
error C2220: warning treated as error - no 'object' file generated
How to fix this error?
The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.
In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.
Go to project properties -> configurations properties -> C/C++ -> treats warning as error -> No (/WX-).
As a side-note, you can enable/disable individual warnings using #pragma. You can have a look at the documentation here
From the documentation:
// pragma_warning.cpp
// compile with: /W1
#pragma warning(disable:4700)
void Test() {
int x;
int y = x; // no C4700 here
#pragma warning(default:4700) // C4700 enabled after Test ends
}
int main() {
int x;
int y = x; // C4700
}
This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):
warning C4101: 'i': unreferenced local variable
After I commented this unused i, and compiled it, the other error went away.
This warning is about unsafe use of strcpy. Try IOBname[ii]='\0'; instead.
Related
I'm trying forward declare my functions in a namespace. But I get an error.
Let me show my .h and .cpp files first.
Header:
namespace DeviceList
{
int GetIDFromType(NNBSSString type);
NNBSSString GetTypeFromID(int id);
void CNNBSSDeviceListAddDevice(NNBSSString& DeviceName, NNBSSString& Address, int DeviceType,
__STRING__ DeviceNetName, __STRING__ DevicePath);
void CNNBSSDeviceListRemoveSelected();
void CNNBSSDeviceListRemoveCache(int index);
inline void CNNBSSDeviceListAddressConnectionRespond(NNBSSString& deviceAddress, bool OK, NNBSSThread* thread);
void CNNBSSDeviceListUpdate();
}
And Source file:
namespace DeviceList
{
int GetIDFromType(NNBSSString type)
{
int m_id;
if (type == _("USB Camera"))
{
m_id = NNBSS_EVT_DEVICETYPE_USBCAM;
}
else if (type == _("IP Camera"))
{
m_id = NNBSS_EVT_DEVICETYPE_IPCAM;
}
else if (type == _("Microphone"))
{
m_id = NNBSS_EVT_DEVICETYPE_MICROPHONE;
}
else if (type == _("DVR"))
{
m_id = NNBSS_EVT_DEVICETYPE_DVR;
}
else if (type == _("NVR"))
{
m_id = NNBSS_EVT_DEVICETYPE_NVR;
}
else
{
m_id = -100;
NNBSSErrorShow("Given DeviceType was wrong while getting int from NNBSSString!", 100);
}
return m_id;
}
NNBSSString GetTypeFromID(int id)
{
// Has to be given by using GetIDFromEnum
NNBSSString m_type;
switch (id)
{
case NNBSS_EVT_DEVICETYPE_USBCAM:
m_type = _("USB Camera");
break;
case NNBSS_EVT_DEVICETYPE_IPCAM:
m_type = _("IP Camera");
break;
case NNBSS_EVT_DEVICETYPE_MICROPHONE:
m_type = _("Microphone");
break;
case NNBSS_EVT_DEVICETYPE_DVR:
m_type = _("DVR");
break;
case NNBSS_EVT_DEVICETYPE_NVR:
m_type = _("NVR");
break;
default:
NNBSSErrorShow("Given DeviceType was wrong while getting NNBSSString from int!", 100);
break;
}
return m_type;
}
void CNNBSSDeviceListAddDevice(NNBSSString& DeviceName, NNBSSString& Address, int DeviceType,
__STRING__ DeviceNetName = __STRING__(), __STRING__ DevicePath = __STRING__())
{
SCNNBSSDeviceParameters params;
params.DeviceName = DeviceName;
params.Address = Address;
params.DeviceType = DeviceType;
params.DeviceNetName = DeviceNetName;
params.DevicePath = DevicePath;
SCNNBSSDeviceParametersList.emplace_back(params);
{
CNNBSSHardwareCheckCameraConnection* p_CNNBSSHardwareCheckCameraConnection =
new CNNBSSHardwareCheckCameraConnection(Address);
p_CNNBSSHardwareCheckCameraConnection->Run();
}
// Update all pages that have Device List active
for (int c = 0; c < (int)m_NNBSSContentPanelList.size(); c++)
{
int pageID = c - 1;
pageID < 0 ? pageID = 0 : pageID = c - 1;
if (CNNBSSDeviceListAddressHandle(m_NNBSSContentPanelList[c])->_IsCreated)
{
CNNBSSDeviceListAddressHandle(m_NNBSSContentPanelList[c])->_RecreateList();
}
}
}
void CNNBSSDeviceListRemoveSelected()
{
if (CNNBSSDeviceListAddressHandle(CNNBSSControlPanelAddressHandle()->_GetCurrentContentPanel())->_IsCreated)
{
CNNBSSDeviceListAddressHandle(CNNBSSControlPanelAddressHandle()->_GetCurrentContentPanel())
->_RemoveSelectedFromList();
}
// Update all pages that have Device List active
for (int c = 0; c < (int)m_NNBSSContentPanelList.size(); c++) {
int pageID = c - 1;
pageID < 0 ? pageID = 0 : pageID = c - 1;
if (CNNBSSDeviceListAddressHandle(m_NNBSSContentPanelList[c])->_IsCreated)
{
CNNBSSDeviceListAddressHandle(m_NNBSSContentPanelList[c])->_RecreateList();
}
}
}
void CNNBSSDeviceListRemoveCache(int index)
{
if (index < 0)
{
index = 0;
}
if (SCNNBSSDeviceParametersList.size() < index)
{
index = (int)SCNNBSSDeviceParametersList.size();
}
auto itr = SCNNBSSDeviceParametersList.begin();
std::advance(itr, index);
if (itr != SCNNBSSDeviceParametersList.end())
{
SCNNBSSDeviceParametersList.erase(itr);
}
}
void CNNBSSDeviceListAddressConnectionRespond(NNBSSString& deviceAddress, bool OK, wxThread* thread)
{
for (int c = 0; c < (int)SCNNBSSDeviceParametersList.size(); c++)
{
if (SCNNBSSDeviceParametersList[c].Address == deviceAddress)
{
if (OK)
{
SCNNBSSDeviceParametersList[c].DeviceConnectionStatus = NNBSS_DEVICE_CONNECTION_STATUS_STRING_ONLINE;
}
else
{
SCNNBSSDeviceParametersList[c].DeviceConnectionStatus = NNBSS_DEVICE_CONNECTION_STATUS_STRING_UNKNOWNERROR;
}
break;
}
}
// Update all pages that have Device List active
for (int c = 0; c < (int)m_NNBSSContentPanelList.size(); c++)
{
int pageID = c - 1;
pageID < 0 ? pageID = 0 : pageID = c - 1;
if (CNNBSSDeviceListAddressHandle(m_NNBSSContentPanelList[c])->_IsCreated)
{
CNNBSSDeviceListAddressHandle(m_NNBSSContentPanelList[c])->_RecreateList();
}
}
// Delete thread
thread->Delete();
delete thread;
}
void CNNBSSDeviceListUpdate()
{// Whenever a USB device is connected, this function will be called automatically
{
std::vector<__STRING__> currentDevices, currentDevicePaths;
CNNBSSHardwareAddressHandle()->GetConnectedUSBCameraList(currentDevices, currentDevicePaths);
// Update all pages that have Device List active
for (int c = 0; c < (int)m_NNBSSContentPanelList.size(); c++)
{
int pageID = c - 1;
pageID < 0 ? pageID = 0 : pageID = c - 1;
if (CNNBSSDeviceListAddressHandle(m_NNBSSContentPanelList[c])->_IsCreated)
{
CNNBSSDeviceListAddressHandle(m_NNBSSContentPanelList[c])->_RecreateList();
}
}
}
}
The problem is, when I remove inline keyword before CNNBSSDeviceListAddressConnectionRespond function, compiler throws an error though for others compiler does not do the same. I wonder, why others works without inline but not CNNBSSDeviceListAddressConnectionRespond function?
Additionally, the complete error message:
Severity Code Description Project File Line Suppression State
Error LNK1169 one or more multiply defined symbols found NNBSS NNBSS\Build\Debug\NNBSS.exe 1
Error LNK2005 "void __cdecl DeviceList::CNNBSSDeviceListAddressConnectionRespond(class NNBSSString &,bool,class NNBSSThread *)" (?CNNBSSDeviceListAddressConnectionRespond#DeviceList##YAXAEAVNNBSSString##_NPEAVNNBSSThread###Z) already defined in ClassManager.obj NNBSS NNBSS\Build\Thread.obj 1
I use include guards.
And my header file is included by over 128 files.
If anything's missing here, let me know
It seems you are using VS2019. I had the same problem and as internet says we're not alone. So, it's a bug that will be fixed once you rebuild the project.
I am trying to build the below code in Visual Studio and get the following error in the last 10 lines: Error: Expression must have pointer-to-object type.
Can somebody take a look and tell me what is missing here.
Here is the code:
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct emptyPeak
{
unsigned int t;
int accel;
}peaks[10];
struct ts0
{
int dt;
int N;
float NValid;
double t0;
int data[36];
int v[36];
};
struct emptyPeakConstant
{
int minSeparation_ms;
int minLocalRange;
float minRangeFraction;
int localRangeHalfWidth_ms;
};
int findAccExtrema()
{
int tStart = 10, tEnd = 5;
unsigned int candidate_t;
int type = 0;
int NPeaks=2;
int n, m, L;
struct emptyPeak peaks;
struct emptyPeakConstant pc;
struct ts0 ts0copy;
pc.minSeparation_ms = 325;
pc.minLocalRange=696;
pc.minRangeFraction=0.62;
pc.localRangeHalfWidth_ms=250;
if(ts0copy.dt==0 || ts0copy.N<3 || ts0copy.NValid<3)
{
return 0;
}
int findMaxima;
if(type == 0 || type == 2)
{
findMaxima = 1;
}
else
{
findMaxima=0;
}
int findMinima;
if(type == 1 || type == 2)
{
findMinima = 1;
}
else
{
findMinima=0;
}
L=round(pc.localRangeHalfWidth_ms/ts0copy.dt);
int minAcc=ts0copy.data[0];
int maxAcc=ts0copy.data[0];
int mnAcc=0;
int K=0;
for(n=0;n<=ts0copy.N-1;n++)
{
if(~ts0copy.v[n])
{
continue;
}
if(ts0copy.data[n] > maxAcc)
{
maxAcc=ts0copy.data[n];
}
if(ts0copy.data[n] < minAcc)
{
minAcc=ts0copy.data[n];
}
mnAcc=mnAcc+ts0copy.data[n];
K=K+1;
}
if(K==0)
{
return 0; // Instead of return in the matlab code
}
mnAcc=mnAcc/K;
float thresholdMaxima = minAcc + pc.minRangeFraction*(maxAcc - minAcc);
float thresholdMinima = maxAcc - pc.minRangeFraction*(maxAcc - minAcc);
for(n=1;n<=ts0copy.N-2;n++)
{
candidate_t=ts0copy.t0 + n*ts0copy.dt;
if(candidate_t<tStart || candidate_t > tEnd || ~ts0copy.v[n])
{
continue;
}
int hasMaxima;
if(findMaxima && (ts0copy.data[n] >= thresholdMaxima) && (ts0copy.data[n] >=ts0copy.data[n-1]) && (ts0copy.data[n] >= ts0copy.data[n+1]))
{
hasMaxima = 1;
}
else
{
hasMaxima = 0;
}
int hasMinima;
if(findMinima && (ts0copy.data[n] <= thresholdMinima) && (ts0copy.data[n] <=ts0copy.data[n-1]) && (ts0copy.data[n] <= ts0copy.data[n+1]))
{
findMinima = 1;
}
else
{
findMinima = 0;
}
if(!hasMaxima && !hasMinima)
{
continue;
}
int maxDelta = 0;
for(m=n-L;m<=n+L;m++)
{
if(m<0 || m>(ts0copy.N-1))
{
continue;
}
unsigned int delta = abs(ts0copy.data[m] - ts0copy.data[n]);
if(ts0copy.v[m] && delta > maxDelta)
{
maxDelta=delta;
}
}
if(maxDelta < pc.minLocalRange)
{
continue;
}
if(NPeaks == 0 || (candidate_t - peaks[NPeaks-1].t) > pc.minSeparation_ms)
{
NPeaks=NPeaks+1;
}
else if(abs(ts0copy.data[n]-mnAcc) < abs(peaks[NPeaks-1].accel-mnAcc))
{
continue;
}
}
peaks[NPeaks-1].t = candidate_t;
peaks[NPeaks-1].accel=ts0copy.data[n];
return NPeaks;
}
There are a few issues in the code (without necessarily resolving the actual issue).
1) did you really want to do
struct emptyPeak
{
unsigned int t;
int accel;
}peaks[10];
?
or did you mean
struct emptyPeak
{
unsigned int t;
int accel;
peaks[10];
}
2) if you did declare the above struct correctly, then did you also mean to declare a variable inside of your function findAccExtrema() as such:
struct emptyPeak peaks;
because now you are operating on a struct, that is NOT an array, as if it is an array. This is probably why you are seeing the issue that you are.
I attended a class of C++, not like all my students, I bought a Mac using xcode to run and edit my files. But recently there is a piece of code, that can be well ran in Ubuntu system, but in my mac, it kept giving me error.
the error appears in this line: char (*maze)[width] = reinterpret_cast (m_maze);
and there are 3 lines with the same above content. if you use the code in Ubuntu, it runs successfully, but in mac, it terminates and report 3 same errors.
the warn said: can not initialize a type of type 'char()[width]' with an rvalue of 'char()[width] '
Plz help
the code is about a mouse in a MAZE.
here are the codes:
#include <iostream>
#include <stdexcept>
#include <cstdlib>
#include <cstdio>
using namespace std;
const char MOUSE = '*';
const char WAY = ' ';
const char WALL = '#';
const char PASS = '.';
const char IMPASS = 'X';
typedef enum tag_Direction {
EDIR_RIGHT,
EDIR_DOWN,
EDIR_LEFT,
EDIR_UP
} EDIR;
class Stack {
public:
Stack (void) : m_top (NULL) {}
~Stack (void) {
for (Node* next; m_top; m_top = next) {
next = m_top -> m_next;
delete m_top;
}
}
void push (EDIR dir) {
m_top = new Node (dir, m_top);
}
EDIR pop (void) {
if (! m_top)
throw underflow_error ("Underflow of Stack!");
EDIR dir = m_top -> m_dir;
Node* next = m_top -> m_next;
delete m_top;
m_top = next;
return dir;
}
private:
class Node {
public:
Node (EDIR dir, Node* next) : m_dir (dir),
m_next (next) {}
EDIR m_dir;
Node* m_next;
};
Node* m_top;
};
class Mouse {
public:
Mouse (size_t x, size_t y) : m_x (x), m_y (y),
m_total (0), m_valid (0) {}
size_t getx (void) const {
return m_x;
}
size_t gety (void) const {
return m_y;
}
size_t gettotal (void) const {
return m_total;
}
size_t getvalid (void) const {
return m_valid;
}
void stepright (void) {
m_x++;
remember (EDIR_RIGHT);
}
void stepdown (void) {
m_y++;
remember (EDIR_DOWN);
}
void stepleft (void) {
m_x--;
remember (EDIR_LEFT);
}
void stepup (void) {
m_y--;
remember (EDIR_UP);
}
void stepback (void) {
switch (recall ()) {
case EDIR_RIGHT:
m_x--;
break;
case EDIR_DOWN:
m_y--;
break;
case EDIR_LEFT:
m_x++;
break;
case EDIR_UP:
m_y++;
break;
}
}
private:
void remember (EDIR dir) {
m_brain.push (dir);
m_total++;
m_valid++;
}
EDIR recall (void) {
EDIR dir = m_brain.pop ();
m_total++;
m_valid--;
return dir;
}
size_t m_x;
size_t m_y;
size_t m_total;
size_t m_valid;
Stack m_brain;
};
class Game {
public:
Game (size_t width, size_t height) :
m_width (width), m_height (height),
m_maze (new char[width * height]),
m_mouse (0, 1) {
if (height < 3)
throw invalid_argument ("The maze is too small!");
srand (time (NULL));
char (*maze)[width] = reinterpret_cast<char (*)[width]> (m_maze);**
for (size_t i = 0; i < height; i++)
for (size_t j = 0; j < width; j++)
if (i == m_mouse.gety () &&
j == m_mouse.getx ())
maze[i][j] = MOUSE;
else
if ((i == 1 && j < 4) ||
(i == height - 2 && j >width-5))
maze[i][j] = WAY;
else
if (i == 0 || i == height - 1 ||
j == 0 || j == width - 1)
maze[i][j] = WALL;
else
maze[i][j] =
rand () % 4 ? WAY : WALL;
}
~Game (void) {
if (m_maze) {
delete[] m_maze;
m_maze = NULL;
}
}
void run (void) {
for (show (); ! quit () && step (););
}
private:
void show (void) {
char (*maze)[m_width] = reinterpret_cast<char (*)[m_width]> (m_maze);
for (size_t i = 0; i < m_height; i++) {
for (size_t j = 0; j < m_width; j++)
cout << maze[i][j];
cout << endl;
}
cout << "Total steps:" << m_mouse.gettotal ()
<< ",Valid steps:" << m_mouse.getvalid ()
<< endl;
}
bool quit (void) {
cout << "Press<Q>to exit,Other keys to continue..."<<flush;
int ch = getchar ();
cout << endl;
return ch == 'Q' || ch == 'q';
}
bool step (void) {
char (*maze)[m_width] = reinterpret_cast<char (*)[m_width]> (m_maze);
size_t x = m_mouse.getx ();
size_t y = m_mouse.gety ();
if (x + 1 <= m_width - 1 && maze[y][x + 1] == WAY) {
maze[y][x] = PASS;
m_mouse.stepright ();
}
else
if (y + 1 <= m_height - 1 &&
maze[y + 1][x] == WAY) {
maze[y][x] = PASS;
m_mouse.stepdown ();
}
else
if (x - 1 >= 0 &&
maze[y][x - 1] == WAY) {
maze[y][x] = PASS;
m_mouse.stepleft ();
}
else
if (y - 1 >= 0 &&
maze[y - 1][x] == WAY) {
maze[y][x] = PASS;
m_mouse.stepup ();
}
else {
maze[y][x] = IMPASS;
m_mouse.stepback ();
}
x = m_mouse.getx ();
y = m_mouse.gety ();
maze[y][x] = MOUSE;
show ();
if (x == 0 && y == 1) {
cout << "I can't get out!cry~~~~" << endl;
return false;
}
if (x == m_width - 1 && y == m_height - 2) {
cout << "I am OUT!!!" << endl;
return false;
}
return true;
}
size_t m_width;
size_t m_height;
char* m_maze;
Mouse m_mouse;
};
int main (int argc, char* argv[]) {
if (argc < 3) {
cerr << "Method:" << argv[0] << " <width> <height>"
<< endl;
return -1;
}
try {
Game game (atoi (argv[1]), atoi (argv[2]));
game.run ();
}
catch (exception& ex) {
cout << ex.what () << endl;
return -1;
}
return 0;
}
char (*maze)[width] = reinterpret_cast<char (*)[width]> (m_maze);
is not standard: warning: ISO C++ forbids variable length array 'maze' [-Wvla].
You have to use
m_maze[y * width + x]
instead of
maze[y][x]
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.
As an exercise (largely an exercise in trying to write something using pointers), I'm writing a cache simulation, specifically of the pseudo least recently used system from the old 486. I'm getting an "Access violation reading location" error on the line:
int min = treeArray[set]->root->findPLRU();
Initially the treeArray seems to be initialised properly (if I pause the program at the start and take a look, it's all as should be), but when the programme breaks and I delve in to examine things the root of the tree in question isn't defined.
I feel it's quite probable that I'm making some sort of very elementary pointer mistake, which is causing the pointer to the node to be "lost" somewhere, but I've no clue what it might be. Is there something in particular I need to do to "hold on" to a pointer value?
#include "stdafx.h"
#include "stdlib.h"
#include <conio.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <io.h>
#include "main.h"
//char fn[80]; // trace filename
int tf; // trace file
trace buf[BUFSZ / sizeof(trace)]; // buffer SIZE
int LRUHits = 0;
int pLRUHits = 0;
int randomHits = 0;
int height;
int cachelinenumber;
//log2 helper function
int log2(int n)
{
int i = 0;
while (n)
{
n = n >> 1;
i++;
}
return i - 1;
}
class CacheLine{
public:
int tag;
int access;
CacheLine();
};
class Cache;
class Node{
public:
bool goRight;
Node* left;
Node* right;
int leftCacheLine;
int rightCacheLine;
Node(int depth) // constructor
{
goRight = false;
if (depth < height - 1)
{
left = new Node(depth + 1);
right = new Node(depth + 1);
leftCacheLine = -1;
rightCacheLine = -1;
}
else
{
leftCacheLine = cachelinenumber;
cachelinenumber++;
rightCacheLine = cachelinenumber;
cachelinenumber++;
}
//printf("Depth: %d, Height: %d, Left: %d, Right: %d\n", depth, height, leftCacheLine, rightCacheLine);
}
~Node()
{
delete left;
delete right;
}
int findPLRU()
{
if (leftCacheLine < 0 || rightCacheLine < 0)
{
if (goRight)
{
goRight = false;
return right->findPLRU();
}
else
{
goRight = true;
return left->findPLRU();
}
}
else
{
if (goRight)
{
goRight = false;
return rightCacheLine;
}
else
{
goRight = true;
return leftCacheLine;
}
}
}
};
class Tree{
public:
Node* root;
Tree()
{
root = new Node(0);
}
~Tree()
{
delete root;
}
};
//cache class
class Cache
{
public:
CacheLine *cache;
int l, k, n, replacementPolicy;
int log2l, log2n;
int access;
Tree** treeArray;
//constructor
Cache(int ll, int kk, int nn, int _replacementPolicy)
{
l = ll;
k = kk;
n = nn;
replacementPolicy = _replacementPolicy;
log2l = log2(l);
log2n = log2(n);
cache = (CacheLine*)malloc(sizeof(CacheLine)*k*n);
for (int i = 0; i < k*n; i++)
{
cache[i].tag = 0x80000000;
cache[i].access = 0;
}
if (replacementPolicy == 1)
{
cachelinenumber = 0;
treeArray = new Tree*[n];
for (int i = 0; i < n; i++)
{
treeArray[i] = new Tree();
}
}
access = -1;
}
//destructor
~Cache()
{
free(cache);
}
//test for hit
void hit(int a)
{
access++;
int set = (a >> log2l) & (n - 1);
int tag = a >> (log2n + log2l);
CacheLine* c = &cache[set*k];
for (int i = 0; i < k; i++)
{
if (c[i].tag == tag)
{
c[i].access = access;
if (replacementPolicy == 0)
LRUHits++;
else if (replacementPolicy == 1)
pLRUHits++;
else if (replacementPolicy == 2)
randomHits++;
break;
}
}
if (replacementPolicy == 0) //LRU
{
int min = 0;
int minv = c[0].access;
for (int i = 1; i < k; i++)
{
if (c[i].access < minv)
{
minv = c[i].access;
min = i;
}
}
c[min].tag = tag;
c[min].access = access;
}
else if(replacementPolicy == 1) // pseudoLRU
{
int min = treeArray[set]->root->findPLRU();
c[min].tag = tag;
c[min].access = access;
}
else // random
{
srand(clock());
int randomNumber = rand()%k;
c[randomNumber].tag = tag;
c[randomNumber].access = access;
}
return;
}
};
void analyse (int l, int k, int n)
{
height = log2(k) + 1;
char fn[] = "ico0.trace";
if ((tf = open(fn, _O_RDONLY | _O_BINARY )) == -1) {
printf("unable to open file %s\n", fn);
exit(0);
}
LRUHits = 0;
pLRUHits = 0;
randomHits = 0;
Cache *cache0 = new Cache(l, k, n, 0); // LRU
Cache *cache1 = new Cache(l, k, n, 1); // pseudoLRU
Cache *cache2 = new Cache(l, k, n, 2); // random
int bytes, word0, a, type, burstcount;
int hits = 0;
int tcount = 0;
while (bytes = read(tf, buf, sizeof(buf)))
{
for (int i = 0; i < bytes / (int) sizeof(trace); i++, tcount++)
{
word0 = buf[i].word0;
a = (word0 & ADDRESSMASK) << 2;
type = (word0 >> TYPESHIFT) & TYPEMASK;
burstcount = ((word0 >> BURSTSHIFT) & BURSTMASK) + 1;
cache0->hit(a);
cache1->hit(a);
cache2->hit(a);
}
}
printf("Hits: %d Total: %d\n", LRUHits, tcount);
printf("Hits: %d Total: %d\n", pLRUHits, tcount);
printf("Hits: %d Total: %d\n\n\n", randomHits, tcount);
delete cache0;
delete cache1;
delete cache2;
}
int _tmain(int argc, _TCHAR* argv[])
{
//analyse(16, 1, 8);
analyse(16, 2, 512);
//analyse(16, 4, 256);
//analyse(16, 8, 128);
//analyse(16, 1024, 1);
_getch();
return 0;
}
Your question hasn't yet been pounced upon, probably because your code still doesn't compile since you've not provided main.h.
And even then it would annoy most folks trying to help you because you make no mention of the ico0.trace file that is required to prevent the code from immediately exiting.
You say int min = treeArray[set]->root->findPLRU(); access violates.
1) the value of set can never exceed the size n of your treeArray since you & n-1 the range of input values.
2) since your ~Tree() destructor is never called there will always be a treeArray[set]->root
3) since you *always create new left & right nodes whenever leftCacheLine = -1 or rightCacheLine = -1 it cannot be due to recursive findPLRUs
So, the pointer to the node is not being "lost" somewhere; it is being stomped on.
Try replacing:
int min = treeArray[set]->root->findPLRU();
c[min].tag = tag;
c[min].access = access;
with:
int min = treeArray[set]->root->findPLRU();
if (min >= k*n)
{
printf("ook\n");
}
else
{
c[min].tag = tag;
c[min].access = access;
}
and I think you will discover what's doing the stomping. ;)