Malloc 不为 char* 分配内存

Mat*_*att 0 c string malloc char

我使用 malloc() 和字符串得到了一个简单的、意想不到的结果。代码:

int main(void) {

char* b64str;
char* binStr = "00000101";

printf("Expected size of allocated structure (b64str): 8\n");
b64str = (char*)malloc((strlen(binStr)+1)*sizeof(char));
printf("Actual size of allocated structure (b64str): %d\n\n", strlen(b64str));
Run Code Online (Sandbox Code Playgroud)

输出:

Expected size of allocated structure (b64str): 8
Actual size of allocated structure (b64str): 0
Run Code Online (Sandbox Code Playgroud)

为什么?

dbu*_*ush 5

您为 分配了空间b64str,但该空间未初始化。尝试调用strlen该缓冲区会引发未定义的行为。在您的特定情况下,第一个字节恰好设置为 0,但您不能依赖该行为。

通过查看无法得知分配了多少内存。您需要自己跟踪它。

如果想查看分配是否失败,请检查返回的指针是否为NULL

b64str = (char*)malloc((strlen(binStr)+1)*sizeof(char));
if (b64str == NULL) {
    perror("malloc failed");
    exit(1);
}
Run Code Online (Sandbox Code Playgroud)