SEGMENTATION FAULT in C++ - Rougewave (only in linux and not in unix)

486 views Asked by At

Hi I am facing memory fault with my code. I used gdb and found out where memory fault occurs. But I am not able to solve that. The lines of code where memory fault occurs is below. Please help me friends.

void CJob::print_parm_file(){
int m_nFuncid;
CCmdset*  pCmdset = NULL;
const int size=1024;
char      fname[80];
char      dbg_buf[size]="";
unsigned int i, gotit=0;

for (i=0; i < entries(); i++)
{
pCmdset  = (CCmdset*)  at(i);

//RWCollectableString *cmdset = (RWCollectableString *)pCmdset->at(0);
//RWCString m_Function=cmdset->data();

CXmlobj *xobj = (CXmlobj *)pCmdset->at(0);

cout <<"The value of m_name.data() //segfault issue is : " << xobj->m_name << endl;
cout <<"The value of m_name.data() //segfault issue is : " << xobj->m_name.data() << endl;
RWCString m_Function=xobj->m_name.data();  //segmentation fault occurs in this line

I have printed the value of m_name.data() to check its value. when i tried printing its value, segmentation fault occured in cout statements itself.

NOTE : This issue is happening only in Linux server. The code is working perfect in Unix server without any issue.

Please help me ! Thanks !!!

2

There are 2 answers

17
Eric Z On

My educated guess is that m_name is of type std::string. There is no guarantee that a null character terminates the character sequence pointed by the value returned by data(). Simply put, your prints may access more elements than that string actually contains which causes this segmentation fault.

Try adding a \0 character at the end of the string, or replace data() with c_str() which is guaranteed to be null-terminated.

3
PaulMcKenzie On

Did you first establish that xobj is valid?

CXmlobj *xobj = (CXmlobj *)pCmdset->at(0);  // if xobj is invalid
xobj->m_name.data();   // ... then this will invoke undefined behavior

The simplest thing to try is just assign that string variable to a temporary string variable and see what happens. If you still get a segmentation fault, then the problem is more than likely that xobj is not pointing to a valid CXmlobj.