c – 为什么这有效? C中的字符指针
发布时间:2020-12-16 10:41:02 所属栏目:百科 来源:网络整理
导读:参见英文答案 This malloc shouldn’t work????????????????????????????????????5个 #include stdio.h#include stdlib.h#include iostreamint main(){ char* s = (char*)malloc(sizeof(char) * 3); //I allocate memory for 3 chars s[0] = 'a'; s[1] = 'b'
参见英文答案 >
This malloc shouldn’t work????????????????????????????????????5个
#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] = ' '; s[3] = 'd'; //This shouldn't work std::cout << s[3] << std::endl; //It prints out d,why? free(s); return 0; } 为什么我被允许写s [3]? 解决方法
通常函数malloc为示例16分配一些最小字节数,即使您将请求仅分配一个(或在示例中为3个)字节.
但是,您不应该依赖该功能的这种功能.实现定义了malloc如何分配内存.所以你的代码有不确定的行为. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读