让我先说一下,我是一个新手,我在学校的入门级C班.
我正在编写一个程序,要求我使用malloc和malloc在所有情况下分配8倍我期望的空间.即使只是对malloc(1),它是分配8个字节而不是1,我很困惑为什么.
这是我测试过的代码.这应该只允许输入一个字符加上转义字符.相反,我可以输入8,所以它是分配8 bytes而不是1,即使我只使用一个整数,也是如此malloc().请忽略该x变量,它在实际程序中使用,但不在此测试中.:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc ,char* argv[]){
int x = 0;
char *A = NULL;
A=(char*)malloc(sizeof(char)+1);
scanf("%s",A);
printf("%s", A);
free(A);
return 0;
}
Run Code Online (Sandbox Code Playgroud)