我写了一些代码来看看如何malloc()
和memset()
表现,我发现了一个我不知道发生了什么的情况.
我曾经malloc()
为字符数组分配15个字节的内存,我想看看如果我memset()
错误地在我创建的指针中设置了100个字节的内存会发生什么.我希望看到它memset()
设置了15个字节(并且可能会丢弃一些其他内存).我在运行程序时看到的是它为我编码的字符设置了26个字节的内存.
知道为什么为我创建的指针分配了26个字节?我正在用gcc和glibc编译.这是代码:
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#define ARRLEN 14
int main(void) {
/* + 1 for the null terminator */
char *charptr = malloc((sizeof(*charptr) * ARRLEN) + 1);
if (!charptr)
exit(EXIT_FAILURE);
memset(charptr, '\0', (sizeof(*charptr) * ARRLEN) + 1);
/* here's the intentionally incorrect call to memset() */
memset(charptr, 'a', 100);
printf("sizeof(char) ------ %ld\n", sizeof(char));
printf("sizeof(charptr) --- %ld\n", sizeof(charptr));
printf("sizeof(*charptr) --- %ld\n", sizeof(*charptr));
printf("sizeof(&charptr) --- %ld\n", …
Run Code Online (Sandbox Code Playgroud)