gpt4 book ai didi

c - 字符串运行时错误仅适用于 getchar 为什么?

转载 作者:行者123 更新时间:2023-11-30 21:07:38 25 4
gpt4 key购买 nike

i am using visual studio 2013 for desktop and i have run time fail with the string i don't know why this isn't working.

    int main(void)
{
char string[MAX1] = "THANK ";
char you[MAX2] = "u";
strncat(string, you, 1); //without fix this line or the next one
printMessage(string);
return 0;
}

it is running only when i am putting getchar at the end. it is working with other programs like notepad++.

MAX1=7. MAX2=2.

最佳答案

string[] 的连接内容(如果有效)将是 THANK u'\0' 即8 个字符。

但是,只分配了 7 个字符。

对 strcat() 的调用不会停止,因此写入超出了数组 string[] 的范围。结果是未定义的行为,并可能导致段错误事件。

但是,当使用 strncat() 时,不会复制尾部 NUL 字节。所以 string[] 现在是一个未终止的字符数组。并且对 printMessage() 的调用将不知道在哪里停止打印字符,这又是未定义的行为。

关于c - 字符串运行时错误仅适用于 getchar 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42760237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com