简体   繁体   English

访问大型堆数组时出现分段错误(核心转储)

[英]Segmentation fault (core dumped) when access large heap array

we know Segmentation fault (core dumped) is caused by illegal memory access.But i don't think it's the reason for my program.我们知道分段错误(核心转储)是由非法 memory 访问引起的。但我认为这不是我的程序的原因。
run the following c code on linux, when the variable l=20,it works, but when l=50, i got Segmentation fault (core dumped).在 linux 上运行以下 c 代码,当变量 l=20 时,它可以工作,但是当 l=50 时,我得到分段错误(核心转储)。 my laptop is ubuntu18.04, 8core,16G MEMORY.我的笔记本电脑是 ubuntu18.04, 8core,16G MEMORY。

//
// Created by sakura on 2020/4/11.
//
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

void *emalloc(size_t n);
int main(){
    printf("begin alloc...\n");
    char* rv;
    int l=50;
    for(int i=0;i<l;i++){
        rv=emalloc(1024*1024*100);
        sleep(1);
    }
    printf("finish alloc...\n");

    for(int i=0;i<l;i++){
        for(int j=0;j<1024*1024*100;j++){
             int a = rand();
            rv[i*1024*1024*100+j]=(a%128);
        }
    }
    printf("finish access...\n");
    sleep(300);
    return 0;
}

void fatal(char *s1,char *s2,int n){
    fprintf(stderr,"Error: %s, %s\n",s1,s2);
    exit(n);
}

void *emalloc(size_t n){
    void *rv;
    if((rv=malloc(n))==NULL){
        fatal("out of memory","",1);
    }
    return rv;
}

You got integer overflow when using i = 50 at this line:在此行使用i = 50时出现 integer 溢出:

rv[i*1024*1024*100+j]=(a%128);

This leads to undefined behavior (see this question ).这会导致未定义的行为(请参阅此问题)。

The value of 50*1024*1024*100 is equal to 5242880000 , but the maximum value for the variable of int type (see INT_MAX constant in the limits.h ) is 2147483647 . 50*1024*1024*100的值等于5242880000 ,但int类型变量的最大值(参见limits.h中的INT_MAX常量)为2147483647

I suggest you consider using a different data type for i variable, for example, size_t .我建议您考虑为i变量使用不同的数据类型,例如size_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM