【发布时间】:2014-02-16 13:40:45
【问题描述】:
#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;
}
为什么允许我写 s[3]?
【问题讨论】:
-
为什么人们更喜欢 C/C++ 代码的混合体?
-
因为,在大多数 C 执行环境中,没有什么可以阻止您使用您不“拥有”的存储空间。 (而且因为“数组”在 C 中并不真正存在。在运行时没有任何东西可以识别数组的大小或其他分配。)
-
@devnull 一位朋友让我展示 C++ 的基础知识,我想向他展示 C 中的 char* 和 C++ 中的字符串。这出现了,我无法回答。
-
那是因为在 c 和 c++ 中,没有错误检查。因此,c 和 c++ 代码更快,但容易出错。编码器负责计算边界
标签: c++ c pointers memory-management undefined-behavior