Reputation: 9
I wrote a C++ class named DCstring similar to String class in Java.
class DCstring
{
public:
TCHAR *string;
DCstring();
DCstring(TCHAR * str);
DCstring in();
}
DCstring::DCstring()
{
string=NULL;
}
//constructor to initialize
DCstring::DCstring(TCHAR* temp)
{
_TINT i=0;
string=(TCHAR*)malloc(_tcslen(temp)*sizeof(TCHAR)+1);
for(;i<_tcslen(temp);i++)
string[i]=temp[i];
string[i]=0;
}
//to get input from user
DCstring DCstring::in()
{
wprintf(L"\n Enter the string :");
TCHAR arr[200],*s;
_getts(arr);
_TINT i=0;
string=(TCHAR*)realloc(string,_tcslen(arr)*sizeof(TCHAR)+1);
for(;i<_tcslen(arr);i++)
string[i]=arr[i];
string[i]=0;
return(*this);
}
This works fine. I use this DCstring variable inside a struct and reads & writes that struct object into &from a file using fwrite & fread functions.
typedef struct Stud
{
DCstring name;
}stud;
void InsertToFile(stud *temp,FILE *file)
{
(temp->name)=DCstring();
fflush(stdin);
temp->name=(temp->name).in();
fseek(file,0,SEEK_END);
fwrite(&(*head),sizeof(stud),1,file);
}
void Show(stud *temp,FILE *file)
{
rewind (file ) ;
fread ( &temp,sizeof(stud), 1, file ) ;
wprintf ( L"\n%s",temp->name ) ;
}
This code can read and write data for the 1st time.when I reexecute the code and call Show(stud *temp,FILE *file)
function,it throws an runtime error/exception.
"Unhandled exception at 0x77c815de in StudentRecord.exe: 0xC0000005: Access violation reading location 0x002850a8".
seems like problem in memory.Help me out.
Upvotes: 0
Views: 205
Reputation: 122381
Apart from the poor implementation of your DCString
class (exposed instance variables, lack of destructor, fixed-sized input buffer, and some more) you have failed to understand that writing an instance of your struct stud
won't, in fact, write the contents of the data pointed to by stud.name.string
.
struct stud
contains an instance of DCString
however the memory used to store the string data is on the heap (which you allocated using malloc()
); your code is writing the pointer to the allocated memory, which will be meaningless when you read it back in (certainly in a different session).
You need to provide a read/write DCString
method, which is passed a FILE *
(better would be to use istream
and ostream
, given this is C++) which reads/writes the string contents, allocating new memory during the read.
Upvotes: 2
Reputation: 15009
The problem is here:
public:
TCHAR *string;
This writes out a pointer to the string, so when you read back in you get a pointer that doesn't point to any data, thus your access violation. This question, for instance, discusses serialisation, which is what you probably want to do.
Furthermore:
fflush(stdin);
Is undefined behaviour.
Yet furthermore, you should really use C++ std::string
and std::i/ofstream
.
EDIT I just noticed:
wprintf ( L"\n%s %d %c",temp->name ) ;
You don't have anything matching the %d
and %c
parameters.
Upvotes: 1