由于memcpy,C++程序不会终止

0 c++ memcpy

我目前正在测试memcpy功能.我已经检查了文档,当我不动态分配内存时,一切都适用.但是当我这样做时,程序就不会终止.就像它进入无限循环.

这是代码,我无法理解它为什么会发生,因为一切似乎都没问题.

#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;
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 7

当你调用时,memcpy你需要传递两个指针,以及要复制的对象的大小.指针应该是指向要复制的对象和要复制到的对象的指针.在

memcpy(&newStudent, &student,sizeof(tStudent));
Run Code Online (Sandbox Code Playgroud)

你不这样做.相反,你给它指向指向对象的指针.由于sizeof(tStudent)大于指针的大小,你将开始复制到你不拥有的内存中(因为你复制了指针的值,而不是它们指向的内容)这是未定义的行为并且可以/将导致程序做一些奇怪的事情.

memcpy这里打电话的正确方法是使用

memcpy(newStudent, student,sizeof(tStudent));
Run Code Online (Sandbox Code Playgroud)

也就是说,没有理由使用指针.您的整个代码可以简化为

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;
}
Run Code Online (Sandbox Code Playgroud)