HI!
I have a function which inputs information from cin and outputs them on file stream .
This is a part of the function :
1 2 3 4 5 6 7 8 9
...
//Function : AddNewStudentToFile (from "StudentFuncs.h")
//StudentStreamOutput is the file I'm writing information to it
//GetFirstName and GetLastName return char *
StudentsStreamOutput << endl << TmpStudent.GetFirstName() << endl << TmpStudent.GetLastName () << endl ;
StudentsStreamOutput.close () ;
cout << "TEST" ;
return 1 ;
}
The "TEST" output is shown on the console correctly and the information I enter are written to file , so I think nothing's wrong with my algorithm , but after the function returns and while getting back to main , program crashes (Has stopped working) and this is my main :
1 2 3 4 5 6 7 8
#include "StudentFuncs.h"
int main ()
{
AddNewStudentToFile() ;
cout << "TEST" ;
return 0 ;
}
The "TEST" here is NOT shown on the screen .
I really can't understand if it is my AddNewStudentToFile function or something's wrong with linking .
And in this program I'm using char * (C-Style String) in my Student class . For inputs I get strings and then 'strcpy' them to my memory allocated char * .
like this :
This may not solve your problems. However, you need to allow an extra character for the null terminator of a c-string. FirstName = newchar [input.size () + 1] ;
also, if SetFirstName was called more than once, there would be a memory leak.
Thanks @Chervil
It is solved .
I just can't get it , because I used "cout" for myself to see if the members are set correctly , And they were correct .
Thanks , I totally forgot to +1 for null-terminating charachter .
I guess the reason is that , when the function returns ,; it tries to delete the temporary information and pointers it was working on , BUT as there are two extra '\0's the program can't handle them (still not sure and don't know why)
and @Computergeek01 , in the case of being curious :
Well, I assume the strcpy() would have to put the terminating zero somewhere. In doing so, it would overwrite some adjacent byte of memory. The result of doing that is unpredictable, but it looks as though some important data was corrupted.