簡體   English   中英

由於memcpy,C ++程序未終止

[英]C++ Program doesn't terminate because of 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;
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM