简体   繁体   中英

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.
run the following c code on linux, when the variable l=20,it works, but when l=50, i got Segmentation fault (core dumped). my laptop is 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:

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 .

I suggest you consider using a different data type for i variable, for example, size_t .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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