Reputation: 880
I'm trying to create a piece of shared memory that holds an array of structs. In my current code when i run it i get a segmentation fault. I think I may need to use memcpy but am severely stuck at the moment. Any help would be mch appreciated...
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <unistd.h>
#include "header.h"
int main()
{
key_t key = 1234;
int shmid;
int i = 1;
struct companyInfo * pdata[5];
strcpy(pdata[0]->companyName,"AIB");
pdata[0]->sharePrice = 11.02;
strcpy(pdata[1]->companyName,"Bank Of Ireland");
pdata[1]->sharePrice = 10.02;
strcpy(pdata[2]->companyName,"Permanent TSB");
pdata[2]->sharePrice = 9.02;
strcpy(pdata[3]->companyName,"Bank Od Scotland");
pdata[3]->sharePrice = 8.02;
strcpy(pdata[4]->companyName,"Ulster Bank");
pdata[4]->sharePrice = 7.02;
int sizeOfCompanyInfo = sizeof(struct companyInfo);
int sizeMem = sizeOfCompanyInfo*5;
printf("Memory Size: %d\n", sizeMem);
shmid = shmget(key, sizeMem, 0644 | IPC_CREAT);
if(shmid == -1)
{
perror("shmget");
exit(1);
}
*pdata = (struct companyInfo*) shmat(shmid, (void*) 0, 0);
if(*pdata == (struct companyInfo*) -1)
{
perror("schmat error");
exit(1);
}
printf("name is %s and %f . \n",pdata[0]->companyName,pdata[0]->sharePrice);
exit(0);
}
the header.h file is as follows...
struct companyInfo
{
double sharePrice;
char companyName[100];
};
Upvotes: 1
Views: 3102
Reputation: 22890
pdata
is a table of pointers so you need to create each struct companyInfo
using malloc before being able to access them.
Upvotes: 3
Reputation: 121981
struct companyInfo * pdata[5];
contains an array of 5 uninitialized pointers. You need too allocate memory for each element in the array before using them:
for (int i = 0; i < 5; i++)
{
pdata[i] = malloc(sizeof(companyInfo));
}
or just declare an array of struct companyInfo
as there does not appear to be any need for dynamic allocation:
struct companyInfo pdata[5];
Upvotes: 3