当乘以一个数字到 sizeof(数据类型)和不乘以一个数字时,malloc 有什么区别

run*_*me 1 c malloc

#include <stdio.h>
#include <stdlib.h>

int main() {
    char *buffer = "hello";
    char *words = malloc(6 * sizeof(char));
    int count = 0;

    while (count < 10) {
        *(words+count) = buffer[count];
        count++;
    }

    printf("%s\n", words);
    return 0;
}

Run Code Online (Sandbox Code Playgroud)

我想知道乘以一个数字有什么区别sizeof(char)。

例如,如果我删除 6 (just char *words=malloc(sizeof(char));),代码也可以工作。

我认为它不会起作用,但是当我运行它时它会起作用。

Bar*_*mar 5

malloc(6 * sizeof(char)) 为 6 个字符的数组分配足够的内存。

如果不乘以 6,则只能获得 1 个字符的足够内存。尝试访问任何其他*words会导致未定义行为的字符。

只要count超过 ,您的代码就会导致未定义的行为5。它是在 结束后写作,在 结束后words阅读buffer;这两个都是未定义的。

未定义的行为并不总是会产生错误消息,请参阅为什么在超出数组末尾写入时不会出现分段错误?. 因此,您的代码可能看起来正在运行,但它仍然是错误的,并且将来可能会失败。