我正在编写一个内存分配器,我需要一种方法来在一 block 内存中存储一个整数。这个整数将代表 block 的大小,因此我可以根据指向开头的指针导航到结尾。
这是我的测试示例:
//编辑:为 testInt 声明的空间 int* testInt = new int;
head_ptr = (char*) malloc(4*1024*1024); // Allocate 4MB
// EDIT: Should have used std::fill and std::copy
memset(head_ptr,23,sizeof(int)); // Set Address head_ptr = 12345
memcpy(testInt,head_ptr,sizeof(int)); // Set testInt = head_ptr
printf("testInt = %i",testInt);
这会在倒数第二行引发段错误。
我想做的事情有意义吗?
如果是这样,正确的做法是什么?
非常感谢大家的帮助!!问题解决:-)
最佳答案
原始问题的答案
memset(head_ptr,12345,sizeof(int)); // Set Address head_ptr = 12345
不,它没有。这会将 head_ptr
的第一个 sizeof(int)
字节设置为 12345,这将溢出(除非您使用的架构中一个字节超过 8 位)。
memcpy(testInt,head_ptr,sizeof(int)); // Set testInt = head_ptr
什么是testInt?一个整数*?一个整数?在后一种情况下使用 &testInt。
此外,从您的标签看来,您使用的是 C++ 而不是 C。但是您的代码实际上只是 C,您应该真正使用更安全的 C++ 函数和特性:
- 内存集 -> std::fill
- memcpy -> std::copy
- malloc -> 新建
- printf -> cout 或(更好)Boost::Format
回复您的编辑
int* testInt;
是一个指向整数变量的指针,但它没有被初始化:它将指向一个随机内存区域(我们可以认为它是“随机的”,即使它是不是)。
memcpy
然后将尝试写入您很可能无法访问的随机内存区域,因此这会导致段错误(这意味着“您无法访问这个内存区域”)。
关于c++ - MemSet 和 MemCpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2557804/