为什么这样做?C中的字符指针

oti*_*oza 3 c c++ pointers memory-management undefined-behavior

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

int main()
{
    char* s = (char*)malloc(sizeof(char) * 3); //I allocate memory for 3 chars
    s[0] = 'a';
    s[1] = 'b';
    s[2] = '\0';
    s[3] = 'd'; //This shouldn't work

    std::cout << s[3] << std::endl; //It prints out d, why?

    free(s);        
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么我被允许写s [3]?

SLa*_*aks 6

这称为未定义的行为.

编译器不会阻止你做违法的事情; 但是,编译后的代码可能无法达到预期效果.


Vla*_*cow 5

通常函数malloc为示例16分配一些最小字节数,即使您将请求仅分配一个(或在示例中为3个)字节.

但是,您不应该依赖该功能的这种功能.实现定义了malloc如何分配内存.所以你的代码有不确定的行为.