gpt4 book ai didi

二维数组 : Why there isn't a segmentation fault? 的 C malloc

转载 作者:太空宇宙 更新时间:2023-11-04 00:41:13 25 4
gpt4 key购买 nike

我使用此方法对二维数组执行 malloc,我的来源是 http://c-faq.com/aryptr/dynmuldimary.htmlModify malloc strategy for 2D Array so malloc succeeds :

int
main(int argc, char *argv[])
{
long **array = NULL;

array = malloc(5 * sizeof(long *));
for (int i = 0; i < 5; i++)
array[i] = malloc(3 * sizeof(long));

array[4][2] = 515;
array[4][3] = 212;
array[4][10000] = 3;

printf("%ld\n", array[4][10000]);

return 0;
}

我的问题是,为什么在返回之前执行最后三行中的任何一行时都没有出现段错误?安全吗(忽略free的不存在)?

最佳答案

您正在调用未定义的行为。顾名思义,未定义行为未定义为导致段错误。该代码可以将该内存的值设置为您给它的值,它可以完全忽略分配,或者它可以为我们所知道的一切订购披萨。

关于二维数组 : Why there isn't a segmentation fault? 的 C malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7383172/

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