c - 访问超出为指针分配的内存的索引

标签 c pointers memory malloc

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

int main()
{
    char *p = malloc(10);
    int i;
    for(i=0;i<15;i++)
    {
        p[i]='c';
        printf("INDEX:%d  %c\n",i,p[i]);
    }

    return 0;
}

我不知道为什么在上面的代码中,我只分配了 10 block 内存,但我仍然能够访问指针的第 15 个索引。

我不知道为什么,但我认为这是因为这个指针指向一些随机的内存块,而我只是覆盖了这部分内存,但我只分配了特定数量的内存,所以我不确定为什么它会起作用。

有人可以确认吗?

最佳答案

I'm not sure why in the above code, I only allocated memory of 10 but I am still able to access the 15th index of the pointer.

访问超出您请求的内存会导致未定义的行为。如果程序没有崩溃,您应该认为自己不幸。它会在最不合时宜的时刻表现得很奇怪。

关于c - 访问超出为指针分配的内存的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30181634/

相关文章:

c - 正在研究如何使用函数调用数组来打印所述数组?

c - 使用 nrel 计算太阳高度

c++ - 实现深拷贝

java - Activity 完成运行后无法在 Android 应用程序中释放内存

memory - 如何在 Chrome 中打开许多选项卡但卸载/禁用非事件/非当前选项卡,释放内存和 CPU?

r - 如何从R中的linux进程状态(ps)命令读取输出?

c - 这个clear_mem函数的目的是什么?

c - 从/proc/<pid>/status 获取 pid 和其他进程信息

javascript - 如何解析 Rust 和 WebAssembly 中的函数指针

转换结构指针