0

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;
}

shao
  • 15
  • 3
  • With `for(int i=0;i – chux - Reinstate Monica Apr 11 '20 at 04:31
  • good question. the point rv should only be available to 100MB memory area. buf actually it can access 100MB*20 memory area. don't know why. – shao Apr 11 '20 at 05:54
  • I suspect "buf actually it can access 100MB*20 memory area" is an incorrect conclusion. – chux - Reinstate Monica Apr 11 '20 at 10:59
  • when l=20, use `ps -u` i can see the RSS is 2G – shao Apr 11 '20 at 14:41
  • Yes code _using_ 2G, but has loss [_access_](https://stackoverflow.com/questions/61151959/segmentation-fault-core-dumped-when-access-large-heap-array?noredirect=1#comment108184665_61151959) to 100MB*19 of that due to the [problem](https://stackoverflow.com/questions/61151959/segmentation-fault-core-dumped-when-access-large-heap-array?noredirect=1#comment108183735_61151959). – chux - Reinstate Monica Apr 11 '20 at 16:57
  • i think the reason why i can access is the memory allocted is consecutive – shao Apr 13 '20 at 11:19

1 Answers1

1

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.

jubnzv
  • 1,526
  • 2
  • 8
  • 20