gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:05:37 26 4
gpt4 key购买 nike

此代码执行以下操作:读取“读取”文本文件的内容并将其写入共享内存空间。该代码直到昨天才工作,但今天相同的代码显示段错误。你能帮我找出我哪里出错了吗?

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

}

最佳答案

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

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

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

关于c - 使用共享内存时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60237798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com