2012-03-11 60 views
1

我试图创建一段拥有结构数组的共享内存。在我当前的代码中,当我运行它时,出现了分段错误。我想我可能需要使用memcpy,但目前我严重卡住。任何帮助将是MCH感激...将结构数组保存到共享内存中

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

} 

的header.h文件内容如下......

struct companyInfo 
{ 
    double sharePrice; 
    char companyName[100]; 
}; 
+0

你的代码在哪里发生seg故障?你可以用一个调试器或甚至只是放入'printf()'语句来查看崩溃发生的位置? – chrisaycock 2012-03-11 22:49:35

+0

它似乎不喜欢我给数组赋值,当我strcpy进入pdata [1]发生分段错误。我发现它通过投掷printfs – kev670 2012-03-11 22:55:29

+0

然后它听起来像'pdata [1]'没有正确初始化。幸运的是,下面有几个答案解释了如何解决这个问题。 – chrisaycock 2012-03-11 22:56:41

回答

3
struct companyInfo * pdata[5]; 

包含5个未初始化的指针数组。您需要太多使用前数组中的每个元素分配内存:

for (int i = 0; i < 5; i++) 
{ 
    pdata[i] = malloc(sizeof(companyInfo)); 
} 

或刚刚宣布的struct companyInfo数组,因为没有出现任何需要动态分配:

struct companyInfo pdata[5]; 
+0

谢谢。使用malloc帮了很大忙,摆脱了分段错误。 – kev670 2012-03-11 23:03:48

+0

不幸的是,这并没有使共享内存工作.. http://stackoverflow.com/questions/9660503/c-memory-sharing-across-2-programs – blueshift 2012-03-12 15:44:14

3

pdata是一个指针表,所以你需要使用malloc创建每个struct companyInfo才能访问它们。