简体   繁体   中英

Creating a 2D array in the shared memory

I want to create a program to store data in a 2D array. This 2D array should be created in the shared memory.

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



key_t key;
int shmBuf1id;
int *buf1Ptr;

main(int argc, int *argv[])
{
    createBuf1();

}

createBuf1()
{
  key = ftok(".",'b');
  shmBuf1id = shmget(key,sizeof(int[9][9]),IPC_CREAT|0666);

  if(shmBuf1id == -1 )
  {
    perror("shmget");
    exit(1);
  }

  else
  {
    printf("Creating new Sahred memory sement\n");
    buf1Ptr[3] = shmat(shmBuf1id,0,0);
    if(buf1Ptr == -1 )
    {
      perror("shmat");
      exit(1);
    }


  }

}

But when I run this program it gives a segmentation fault(Core dumped) error. Have I created the 2D array in the shared memory correctly?

First, int *buf1Ptr is a pointer to int. In your case you want a pointer to a 2-dimensional array of integers, so you should declare it as:

int (*buf1Ptr)[9];

Then you need to initialize the pointer itself:

buf1Ptr = shmat(shmBuf1id,0,0);

Now you can access your array through buf1Ptr (ie. buf1Ptr[0][0] = 1 ). Here's a complete working version of your program:

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

key_t key;
int shmBuf1id;
int (*buf1Ptr)[9];

void
createBuf1()
{
  key = ftok(".",'b');
  shmBuf1id = shmget(key,sizeof(int[9][9]),IPC_CREAT|0666);

  if(shmBuf1id == -1 )
  {  
    perror("shmget");
    exit(1);
  }
  else
  {  
    printf("Creating new Sahred memory sement\n");
    buf1Ptr = shmat(shmBuf1id,0,0);
    if(buf1Ptr == (void*) -1 )
    {  
      perror("shmat");
      exit(1);
    }
  }  
}

int
main(int argc, int *argv[])
{
    createBuf1();
    return 0; 
}

you forgot allocate memory:

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



key_t key;
int shmBuf1id;
int *buf1Ptr;

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

}

createBuf1()
{
  key = ftok(".",'b');
  shmBuf1id = shmget(key,sizeof(int[9][9]),IPC_CREAT|0666);

  if(shmBuf1id == -1 )
  {
    perror("shmget");
    exit(1);
  }

  else
  {
    printf("Creating new Sahred memory sement\n");
    int buf1Ptr[4];
    buf1Ptr[3] = shmat(shmBuf1id,0,0);
    if(buf1Ptr == -1 )
    {
      perror("shmat");
      exit(1);
    }


  }

}

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