Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

memory heap allocation 1

Status
Not open for further replies.

home666

Programmer
Feb 23, 2004
5
IT
I use this code for file opening and allocating heap memory:


std::ifstream in;
const char * buffer;
long ptr;
long size;
std::vector<OBJ_T *> objects_list; // list of objects readed by file


int open_file(string Pfile)
{
ptr=0;
in.open(Pfile.c_str());
if (!in.is_open()) die ("Error, could not open ");
in.seekg (0, ios::beg);
long l = in.tellg();
in.seekg (0, ios::end);
long m = in.tellg();
size=m-l;
buffer=new char[size];
in.seekg (0, ios::beg);
in.read ((char *)buffer, size);
return 0;
};


Later in my project, i do a "parsing" in "Pfile" (now in memory heap) and I allocate other memory heap (using 'new') for other objects that I create.
In execution, I get "segmentation fault" error (I work with linux version 9).
Where is my error?
I allocate enough memory or not?
Sorry for my english!
Thank you very much.
 
buffer=new char[size];
in.seekg (0, ios::beg);
in.read ((char *)buffer, size);
You don't terminate the string with a \0, so it isn't a proper 'C' style string.
Which means most of the string.h functions will fail at some point.

So do this
Code:
buffer=new char[size+1];
in.seekg (0, ios::beg);
in.read ((char *)buffer, size);
buffer[size] = '\0';

> In execution, I get "segmentation fault" error (I work with linux version 9).
> Where is my error?
Use a debugger
Code:
# compile with debug
gcc -g -o prog prog.c

# run a debugger
ddd prog

When your program segfaults, the debugger will show you the exact point in your source code where the problem was "detected".
This is only a clue, because typically where a problem is "detected" and where a problem is "caused" are different. You need to find the cause to stand a chance of fixing it.

If you don't have 'ddd' as a debugger, then use 'gdb'


--
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top