如果两段内存重叠,用memcpy函数可能会导致行为未定义,改进:
void* memmove(void* str1,const void* str2,size_t n) { char* pStr1= (char*) str1; const char* pStr2=(const char*)str2; if (pStr1 < pStr2 ) { for(size_t i=0;i!=n;++i) { *(pStr1++)=*(pStr2++); } } else { pStr1+=n-1; pStr2+=n-1; for(size_t i=0;i!=n;++i) { *(pStr1--)=*(pStr2--); } } return (str1); } int main() { // 内存重叠 char c1[] = "hello world"; memmove(c1+3, c1, 8); cout<<"memmove result: "<<c1<<endl; //输出结果:helhello wo memcpy(c1+3,c1,8); //cout<<"memcpy: "<<c1<<endl; // <span style="line-height: 28.7999992370605px; font-family: arial, STHeiti, 'Microsoft YaHei', 宋体;">输出</span><span style="line-height: 28.7999992370605px; font-family: arial, STHeiti, 'Microsoft YaHei', 宋体;">结果:</span><span style="line-height: 28.7999992370605px; font-family: arial, STHeiti, 'Microsoft YaHei', 宋体;">helhelhell0</span> // 内存不重叠 char c2[] = "hello world"; char c3[] = "love you"; memmove(c2,c3,8); //cout<<"memmove result:"<<c2<<endl;//<span style="line-height: 28.7999992370605px; font-family: arial, STHeiti, 'Microsoft YaHei', 宋体;">输出结果:</span><span style="line-height: 28.7999992370605px; font-family: arial, STHeiti, 'Microsoft YaHei', 宋体;">love yourld</span> memcpy(c2,c3,8); cout<<"memcpy: "<<c2<<endl; //输出结果:love yourld memcpy(c1+3,c1,8); }
时间: 2024-10-11 02:11:50