C++ Program doesn't terminate because of memcpy

Malcom

New Member
#1
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.
Mã:
#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;
}
 

Admin

Administrator
Thành viên BQT
#2
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
Mã:
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
Mã:
memcpy(newStudent, student,sizeof(tStudent));
That said, there is no reason to use pointers at all. Your entire code could be simplified to
Mã:
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;
}
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top