【发布时间】:2019-02-04 19:37:05
【问题描述】:
我正在用 C 编写一个程序,下面的函数接受三个参数,并将字符串中的一个字符替换为另一个字符。好吧,大部分都可以正常工作,但是在尝试执行这部分代码时出现错误:str [pos] = ch;。错误提示“访问冲突写入位置 0x0133585B。”
void kstrput(char *str, size_t pos, char ch)
{
if(pos > strlen(str))
{
abort();
}
str[pos] = ch;
}
主要部分:
char *kstr = "hello";
int pos = 3;
char s = '\0';
printf("\n Enter a character ");
scanf("%c", &s);
kstrput(kstr,pos,s); // calling the kstrput function
printf("\n After kstrput: %s",kstr); //printing the struct to check value of the string
【问题讨论】:
-
显示调用函数的代码。您可能正在传递一个不可写的字符串文字。
-
如果
pos == strlen(str)覆盖null终止符,str不再是有效字符串。来自后续print的未定义行为如下。 -
以这种方式使用 strlen 几乎总是错误的:函数的调用者必须给出字符串的长度,因为在函数内部“猜测”它是非常危险的。
标签: c runtime-error