C++ 程序不会因为 memcpy 而终止
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)
大于指针的大小,您将开始复制到您不拥有的内存中(因为您复制的是指针的值,而不是它们指向的值),这是未定义的行为和 can/will 导致程序做奇怪的事情。
这里调用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;
}
我目前正在测试 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)
大于指针的大小,您将开始复制到您不拥有的内存中(因为您复制的是指针的值,而不是它们指向的值),这是未定义的行为和 can/will 导致程序做奇怪的事情。
这里调用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;
}