c - ANSI C strncpy 弄乱了屏幕输出和其他变量的值

标签 c ansi strncpy

使用 ANSI C,屏幕在 strncpy 之后变得困惑。此外,如果我尝试打印任何 int 变量值就会变得不正确。但是,如果我在 strncpy 之前移动打印行,一切都很好。

有人知道为什么吗?

#define TICKET_NAME_LEN 40

struct stock_data 
{
    char ticket_name[TICKET_NAME_LEN+1];
};

struct stock_data user_input;

char tname[TICKET_NAME_LEN+1] = "testing it";

strncpy(user_input.ticket_name, tname, TICKET_NAME_LEN);

最佳答案

您描述的症状是副本失控的典型症状。但是,问题的真正根源几乎肯定不在您显示的代码中。

您显示的代码唯一可能存在的问题是 strncpy() 不保证输出(目标)字符串以 null 终止。这不会对显示的代码造成伤害(它不会做任何不利的事情),但是其他期望字符串以 null 终止的代码在不确保有空间的情况下愉快地复制它可能会践踏其他内存,因为字符串不是 null终止。

如果输入(源)字符串比指定的空间长(在这种情况下超过 TICKET_NAME_LEN 字节长),则 user_input.ticket_name 不会以 null 终止,除非意外。如果它更短,则 user_input.ticket_name 将被空填充到 TICKET_NAME_LEN 字节的长度。

如果这是问题所在,一个非常简单的解决方法是添加以下行:

user_input.ticket_name[TICKET_NAME_LEN] = '\0';

strncpy() 之后(甚至之前,但更传统的做法是在之后)。

但是,要遇到此问题,您必须尝试将 41 个或更多字符的名称复制到结构的票证名称成员中。

更有可能是其他原因导致了您的麻烦。

ISO/IEC 9899:2011 §7.24.2.4 The strncpy function

¶2 The strncpy function copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s1.308) If copying takes place between objects that overlap, the behavior is undefined.

¶3 If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written.

308) Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null-terminated.

关于c - ANSI C strncpy 弄乱了屏幕输出和其他变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19876814/

相关文章:

c - strncpy 导致 LPC-2378 挂起/死亡

c - 查找父文件夹的路径

c - 需要帮助了解缓冲区溢出及其利用

c - 我如何获得 ANSI C 标准的副本?

c - 在 Windows 中不使用回车符 (CR) 将新行打印到文本文件

c - 从 ANSI C 代码获取控制流图

c++ - 在 Windows 上安装 C/C++ 库

c++ - C++ typedef 中的 struct 关键字

c++ - 扑克代码清理修改从书...不太正确

将字符串复制到 malloc 的字符串数组