首页 > 解决方案 > 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;
}

标签: c++memcpy

解决方案


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

memcpy(&newStudent, &student,sizeof(tStudent));

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

在这里调用的正确方法memcpy是使用

memcpy(newStudent, student,sizeof(tStudent));

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

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;
}

推荐阅读