简体   繁体   中英

Segmentation fault while using shared memory

This code performs the following: Reads the contents of the "read" text file and writes it into the shared memory space.The code was working until yesterday but the same code shows segmentation fault today. Can you help me figure out where I'd made a mistake?

#include<sys/ipc.h>
#define NULL 0
#include<sys/shm.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h> 
#include<sys/wait.h> 
#include<ctype.h>
#include<fcntl.h>
#include<stdio_ext.h>

int main()
{

char *a;
char name[20];
int id,n;
char buf[50];
int fd;
fd=open("read",O_RDONLY);   
int s1=read(fd,&buf,50);

id=shmget(200,50,IPC_CREAT);

    a=shmat(id,NULL,0);
    strcpy(a,buf);
    wait(NULL);
    shmdt(a);

shmctl(id,IPC_RMID,NULL);
return 0;

 }

You have to check the return value of every function you used in your code. The segmentation fault occurred when you call strcpy(a,buf); . If you check the value of a it does not have a valid memory address, that is because you never checked the value returned from shmat() call and you need to carefully check the parameters that this function is taking(man page).

Below, I commented where the seg fault occurs:

int main()
{
  //char name[20]; // never used
  int id; 

  char *a;
  char buf[50];
  int fd;
  fd=open("read",O_RDONLY); // check return value
  //make sure you provide the correct path for your "read" text file
  int restlt = read(fd,&buf,50); // check return value


  key_t mem_key = ftok(".", 'a');
  id = shmget(mem_key, 50, IPC_CREAT | 0666);
  //id = shmget(200,50,IPC_CREAT); //check the return value
  if (id < 0) {
      printf("Error occured during shmget() call\n");
      exit(1);
  }
  a = shmat(id,NULL,0); //check the return value
  if ((int) a == -1) {
       printf("Error occured during shmat() call\n");
       exit(1);
  }
  printf("Value of pointer a = %p \n", a);
  strcpy(a,buf); // better to use strncpy(a, buf, n);

  printf("Value of a[0]  = %c \n", *a);

  wait(NULL);
  shmdt(a);
  shmctl(id,IPC_RMID,NULL);

  return 0;

 }

Check out this link: http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/shmat.html

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