简体   繁体   English

由于memcpy,C ++程序未终止

[英]C++ Program doesn't terminate because of memcpy

I'm currently testing memcpy function. 我目前正在测试memcpy函数。 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. 调用memcpy ,需要向其传递两个指针以及要复制的对象的大小。 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. 由于sizeof(tStudent)大于指针的大小,因此您将开始复制到您不拥有的内存中(因为您正在复制指针的值,而不是它们指向的指针),这是未定义的行为,并且可以/会导致程序做奇怪的事情。

The proper way to call memcpy here is to use 在此处调用memcpy的正确方法是使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM