[英]Segmentation fault in array storing in IPC linux
I am trying to store a array in shared from a process and tring to access the same from another process.我正在尝试从一个进程共享一个数组并尝试从另一个进程访问它。
Below is the code I am using to store the array下面是我用来存储数组的代码
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int count;
int main()
{
while(1)
{
int arr[5] = {1,2,3,4,5};
int *str1;
int key=5678;
// shmget returns an identifier in shmid
int shmid = shmget(key,1024, 0666|IPC_CREAT);
printf("\nShared Memory Id = %d\n",shmid);
// shmat to attach to shared memory
str1 = (int*) shmat(shmid,(void*)0,0);
for(int i=0;i<5;i++)
{
*str1=arr[i];
printf("Data written in memory: %d\n",*str1);
str1++;
}
}
shmdt((void*)str);
return 0;
}
When I am running the program, it is running upto some extend and giving error as segmentation fault (core dumped) and getting exit from the application.当我运行程序时,它运行到一定程度并给出错误作为分段错误(核心转储)并退出应用程序。
Please help me to solve this problem.请帮我解决这个问题。
Thanks and regards, Prabhakar M感谢和问候, Prabhakar M
str1++ is the culprit. str1++ 是罪魁祸首。 Below code is working.
下面的代码正在工作。
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int count;
int main()
{
int arr[5] = {1,2,3,4,5};
int *str1;
int key=5678;
// shmget returns an identifier in shmid
int shmid = shmget(key,1024, 0666|IPC_CREAT);
printf("\nShared Memory Id = %d\n",shmid);
// shmat to attach to shared memory
str1 = (int*) shmat(shmid,(void*)0,0);
int *copyAdrr;
copyAdrr = str1 ;
while(1)
{
for(int i=0;i<5;i++)
{
*str1=arr[i];
printf("Data written in memory: %d\n",*str1);
str1++;
}
str1 =copyAdrr;
}
shmdt((void*)str);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.