【发布时间】:2012-10-07 17:50:31
【问题描述】:
好的,我试图实现 memmove 只是作为一个编程练习,当我尝试使用 malloc 时,我在 memmove 函数中遇到内存访问冲突。这是函数:
//Start
void* MYmemmove (void* destination, const void* source, size_t num) {
int* midbuf = (int *) malloc(num); // This is where the access violation happens.
int* refdes = (int *) destination; // A pointer to destination, except it is casted to int*
int* refsrc = (int *) source; // Same, except with source
for (int i = 0;num >= i;i++) {
midbuf[i] = *(refsrc + i); // Copy source to midbuf
}
for (int i = 0;num >= i;i++) {
refdes[i] = *(midbuf + i); // Copy midbuf to destination
}
free(midbuf); // free midbuf
refdes = NULL; // Make refdes not point to destination anymore
refsrc = NULL; // Make refsrc not point to source anymore
return destination;
}
顺便说一句,我是指针的新手,所以如果有一些错误不要感到惊讶。 我做错了什么?
【问题讨论】:
-
您不需要将 malloc 的返回值或实际上任何 void 指针转换为任何其他指针类型。仍在查看您的代码,仅供参考。
-
@Dan:C++ 不是这样,问题也有 C++ 标签。
-
memmove 占用多个字节,但您使用的是整数。
-
memmove的标准库实现不使用中间缓冲区。另外,最后将refdes和refsrc设置为NULL是没有意义的:函数即将返回,因此无法使用。 -
除了
malloc的大小问题,for循环中的比较是错误的;它应该是num > i,而不是num >= i。就风格而言,i < num是常用的写法。