This question already has answers here:
Closed 5 years ago.
Why does this code produce a segmentation fault? [duplicate]
(2个答案)
当从源复制到目标时,程序第一次崩溃,第二次while循环。(
(2个答案)
char* StrCat(char* dest, char* source)
{
char* retVal = dest;
while(*dest)
dest++;
while(*dest++ = *source++) ;
return retVal;
}
int main()
{
char* a = "One";
char* b = "Two";
char* x = StrCat(a, b);
printf("%s\n", x);
return 0;
}
当从源复制到目标时,程序第一次崩溃,第二次while循环。(
Access violation
错误) 最佳答案
变量a和b的内容(字符串“1”和“2”)存储在只读段中,内容受保护,不能覆盖其数据。
另外,StrCat()函数没有太多逻辑。
您需要使用一个全局char数组,或者一个传递给函数的char数组,该函数的大小是有限的,并确保在复制过程中不会超出其缓冲区大小,否则将导致堆栈溢出。
另一个解决方案是使用malloc动态分配内存,当您不再需要它时,应该释放该内存。
重新考虑如何编写这样的函数来更正它,但首先要解决这个内存问题。
关于c - 此串联函数有什么问题? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25997688/