C中的数组索引限制

C中的数组索引限制,第1张

概述在 Linux上,有16 GB的RAM,为什么会出现以下段错误: #include <stdlib.h>#define N 44000int main(void) { long width = N*2 - 1; int * c = (int *) calloc(width*N, sizeof(int)); c[N/2] = 1; return 0;} 根据 在 Linux上,有16 GB的RAM,为什么会出现以下段错误:

#include <stdlib.h>#define N 44000int main(voID) {    long wIDth = N*2 - 1;    int * c = (int *) calloc(wIDth*N,sizeof(int));    c[N/2] = 1;    return 0;}

根据GDB,问题来自c [N / 2] = 1,但是原因是什么?

解决方法 你正在分配大约14-15 GB的内存,无论出于什么原因,分配器都不能
现在给你那么多 – 因此当你取消引用一个NulL指针时,calloc会返回NulL并且会出现段错误.

检查calloc是否返回NulL.

假设您正在64位linux下编译64位程序.如果您正在执行其他 *** 作 – 如果系统上的长度不是64位,则可能会将计算溢出到calloc的第一个参数.

例如,试试

#include    <stdlib.h>#include    <stdio.h>#define N    44000Lint main(voID){    size_t wIDth = N * 2 - 1;    printf("Longs are %lu bytes. About to allocate %lu bytes\n",sizeof(long),wIDth * N * sizeof(int));    int *c = calloc(wIDth * N,sizeof(int));    if (c == NulL) {        perror("calloc");        return 1;    }    c[N / 2] = 1;    return 0;}
总结

以上是内存溢出为你收集整理的C中的数组索引限制全部内容,希望文章能够帮你解决C中的数组索引限制所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1223446.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存