为数组分配的动态内存大小是多少? 例如我们必须打印一个 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/