使用共享内存时出现分段错误

时间:2020-02-15 10:18:55

标签: c ipc shared-memory

此代码执行以下操作: 读取“已读取”文本文件的内容并将其写入共享内存空间。该代码一直运行到昨天,但是同一代码今天显示了分段错误。您能帮我弄清楚我哪里做错了吗?

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

 }

1 个答案:

答案 0 :(得分:1)

您必须检查代码中使用的每个函数的返回值。调用strcpy(a,buf);时发生分段错误。如果您检查a的值,它没有有效的内存地址,那是因为您从未检查过shmat()调用返回的值,因此需要仔细检查此函数使用的参数(手册页)。

下面,我评论了段错误发生的位置:

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;

 }

查看此链接:http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/shmat.html