c++ - 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;
}
解决方案
当您调用时,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;
}
推荐阅读
- mongodb - 在 Windows 8.1 中运行 mongodb 时文件丢失问题
- android - Xamarin.Forms AppCenter 推送通知
- firebase - 如何通过从对话流的内联实现代码调用自定义事件来调用意图?
- django - 如何在 Django admin 中过滤字段(表单)中的选择?
- r - 如何在不使用管道运算符的情况下更改 R(highcharter 包)中 hchart() 函数中的图表高度?
- excel - 宏有效但快捷方式无效 - application.onkey
- java - 使用 Eclipse Code Formatter for Java 在 if() 中缩进条件
- php - Laravel - 集合。如何将数组分成两组
- html - Css左右移动div
- google-places-api - 使用 Google Places API 时在服务器上存储照片