gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:18:43 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com