有关拷贝函数的实现----MS面试题
前几天看了林锐的书,说MS面试他的时候让他写拷贝函数。昨天自己试着写了一下,还是没有写出来,(结果不满意)主要出在当from串的长度大于to 分配的内存时会出问题。(在函数体内无法得到参数所分配内存块的大小)结果在vs6 下,
1) 在Debug下编译链接通过后运行完了后,弹出对话框说DEBUG ERROR
2)在Release下运行结果正常。
为:
f=12345678912345
t=12345678912345
这显然是有问题的。
敢问高手Strcpy()函数到底要咋样写。
//
#include<iostream.h>
#include<assert.h>
#include<string.h>
#include<stdio.h>
void stringcpy(char *to,const char *from) //使用时保证from小于to指向的内存块
{
assert(from!=NULL&&to!=NULL);
while(*from!=0)
{
*to=*from;
to++;
from++;
}
*to=0;
}
void main()
{
char *f,*t;
f=new char[15];
t=new char[10];
//strcpy(t,"wo dslfjlsjflsjfldjsfljds");
//调用c库函数。运行时与stringcpy效果相同
stringcpy(f,"12345678912345"); // f满了
stringcpy(t,f); //t内存越界
cout<<"f="<<f<<endl<<"t="<<t<<endl;
delete f;
delete t;
f=NULL;
t=NULL;
getchar();
}