本文介绍了记忆确实“移动"了吗?大量内存并在源头留下零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内存实际上移动"了一块内存吗?如果是这样,它是否将内存留为零?还是就像 memcpy 一样?我正在看手册页,但我不认为我的假设是正确的.如果我想使用memmove来移动内存块,我是否必须手动将移动所在的内存块清零?

Does memmove actually "move" a chunk of memory? If so, does it leave the memory with zeros? Or, is it just like memcpy? I am looking at the man page, and I do not believe my assumption is correct. If I want to move a chunk of memory using memmove, would I have to manually zero out the chunk of memory where I did the move?

推荐答案

memmove与清除旧内存无关,实际上,只有在您要使用memmove的情况下,清除旧内存内存会破坏您刚刚复制的数据!这是因为memmove仅在您希望源和目标范围重叠时才有用.

memmove has nothing to do with clearing the old memory, and in fact in the only situations where you would want to use memmove, clearing the old memory would destroy the data you just copied! That's because memmove is only useful when you expect the source and destination ranges to overlap.

通常,如果您发现自己需要memmove,则表明您在设计上存在严重的根本性低效率.例如,新的C程序员经常会尝试使用memmove删除字符串的前几个字符(例如memmove(s, &s[1], len)),而不是仅使用s+1&s[1]来寻址字符串的尾部.包含memmove的算法很少有比O(n ^ 2)更好的表现.

Usually, if you find yourself needing memmove, it's indicative that you have a major fundamental inefficiency in your design. For instance, often new C programmers will try to use memmove to remove the first few characters of a string (e.g. memmove(s, &s[1], len)) rather than just using s+1 or &s[1] to address the tail of the string. Algorithms containing memmove rarely perform better than O(n^2).

这篇关于记忆确实“移动"了吗?大量内存并在源头留下零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:41