Gabriel722
Gabriel722

Reputation: 13

how to make shared memory with specific array size?

I got a question about shared memory and segmentation fault. I thought that it would be fine to use huge size of memory. When I checked Shmmax, i found the huge memory can be allocated.

under data is the result of $ipcs -lm

------ Shared Memory Limits --------

max number of segments = 4096

max seg size (kbytes) = 18014398509465599

max total shared memory (kbytes) = 18014398442373116

min seg size (bytes) = 1

#include <stdio.h>
#include <sys/shm.h>
#include <sys/ipc.h> 
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

#define ARRAY_SIZE 40000000


int main(int argc, char *argv[]){

    int shmid;
    void *shared_memory = (void *)0;
    shmid = shmget((key_t)1234, sizeof(float), IPC_CREAT|0666);
    if (shmid == -1)
    {
        perror("shmget failed : ");
        exit(0);
    }

    shared_memory = (float *)shmat(shmid, NULL, 0);
    if (shared_memory == (void *)-1)
    {
        perror("shmat failed : ");
        exit(0);
    }

    static float *testx;
    testx = (float *)shared_memory;

    int k = 0;
    for(k;k<400;k++){
        testx[k] = 1.12;
    }
    for(k;k<40000000;k++){
        testx[k] = 1.12;
    }
}

the program can run the first for loop which has small amount of size

the problem, however, is the second loop with 40,000,000 size

any suggestion what should i edit to run this code?

Upvotes: 0

Views: 1933

Answers (1)

Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

The reason for your SEGFAULT is that you haven't created enough size segment with shmget.

The argument you passed to shmget as size is sizeof(float) which is just enough to store 1 float.

What you need to do is call shmget like this -

shmget((key_t)1234, sizeof(float)*40000000, IPC_CREAT|0666);

Then you can use all the memory correctly.

The reason that the smaller loop of 400 worked is because shmget creates segments that are multiple of PAGE_SIZE.

So even when you passed sizeof(float), it allocated atleast 1 page which was enough to hold 400 floats but not 40000000.

I hope that clears the confusion.

Upvotes: 2

Related Questions