C - 动态分配字符数组

标签 c dynamic-arrays

为数组分配的动态内存大小是多少? 例如我们必须打印一个 len = 4 的数组

int i, n, len = 4;
char *s = malloc(len * sizeof(char));
strcpy(s, "aaabbcc");
n = strlen(s);
printf("%d", n);

输出应该是4,但输出始终是7

最佳答案

在 C 中,您必须为数据分配固定大小的缓冲区。在您的情况下,您分配了 len * sizeof(char),其中 len = 4 字节用于字符串。

来自 strcpy 的文档:

char * strcpy ( char * destination, const char * source );

Copy string Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.

您将大小为 8 的字符串("aaabbcc" 和隐式空终止符)复制到大小为 4 的缓冲区中。这就是所谓的 buffer overflow ;您将字符串复制到小于该字符串所需的缓冲区中。

strlen在字符串中查找空终止符以查找字符串大小。它读取缓冲区溢出的字符串,这就是它返回 7 的原因:缓冲区溢出字符串的大小减去空终止符的一。

请注意,分配正确大小的缓冲区似乎并不重要,但这样做至关重要。溢出的值可能会在内存中被覆盖或覆盖其他内存,从而导致未定义的行为。

关于C - 动态分配字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39559570/

相关文章:

c++ - 对象的动态数组 - 初始化方法之间的区别

c - 使用 switch 语句和函数时程序 (C) 崩溃

c - 从类型 'char *[12]' 分配给类型 'int' 时的类型不兼容

c - C 中神秘的 sprintf 行为 : Second lld param prints as zero (0) always

c++ - 编码 x264(libx264) 原始 yuv 帧数据

c - 在C中将字符串添加到字符指针

c - C中动态分配数组的错误

arrays - 求值,放入数组,求数组VBA中的最小值

返回对象时清除 C++ 动态数组

delphi - 为什么两个 TByte 不能使用重叠数据?