I'm currently testing memcpy function. I've checked documentation and everything applies when I don't dynamically allocate memory. But when I do, the program just doesn't terminate. Like it enters infinite loop.
Here's the code, I can't get to the point of understanding why it happens because everything seems okay.
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
struct tStudent{
int indexNo;
char nameSurname[30];
int year;
};
int main(){
tStudent *student=new tStudent;;
student->indexNo=30500;
strcpy(student->nameSurname,"Ralph Martinson");
student->year=2016;
tStudent *newStudent=new tStudent;
memcpy(&newStudent, &student,sizeof(tStudent));
cout<<"PRINT:\n";
cout<<newStudent->indexNo<<endl;
cout<<newStudent->nameSurname<<endl;
cout<<newStudent->year<<endl;
return 0;
}
When you call memcpy
you need to pass it two pointers, and the size of the object to copy. The pointer should be pointer to the object to copy and the object to copy to. In
memcpy(&newStudent, &student,sizeof(tStudent));
You don't do that. Instead you give it pointers to pointers to the objects. Since sizeof(tStudent)
is larger than the size of a pointer you are going to start copying into memory you don't own (beacuse you are copy the value of the pointers, not what they point to) which is undefined behavior and can/will cause the program to do strange things.
The proper way to call memcpy
here is to use
memcpy(newStudent, student,sizeof(tStudent));
That said, there is no reason to use pointers at all. Your entire code could be simplified to
int main(){
tStudent student; // don't use a pointer. Instead have a value object
student.indexNo=30500;
strcpy(student.nameSurname,"Ralph Martinson");
student.year=2016;
tStudent newStudent = student; // copy initialize newStudent. You get this for free from the compiler
cout<<"PRINT:\n";
cout<<newStudent->indexNo<<endl;
cout<<newStudent->nameSurname<<endl;
cout<<newStudent->year<<endl;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.