【发布时间】:2015-05-14 08:23:37
【问题描述】:
我正在尝试实现我自己的 strncpy() 版本,我从 link 中找到了源代码。
但每次代码到达此代码while((x++ < n) && (*dest++ = *source++));时,我都会遇到Unhandled exception at 0x00411ad5 in exercise 2.exe: 0xC0000005: Access violation writing location 0x00417800.
完整代码如下:
char *strncpy(char * destination, const char * source, size_t n){
char *dest;
dest = destination;
size_t x=0;
while((x++ < n) && (*dest++ = *source++)); //this is where unhandled exception occurs
while(x++ < n){
*dest++ = 0;
}
return dest;
}
int main(){
char *sample = "blue";
char * sample2 = "red";
cout << strncpy(sample, sample2, 5);
getch();
return 0;
}
请告诉我为什么会发生这种情况以及我应该如何解决它?谢谢!
【问题讨论】:
-
您不能覆盖为文字保留的内存。
-
出现错误是因为你写入了一个只读字符串
sample。 -
您不是要返回
destination,而不是已经结束的dest吗?