日期:2014-05-16  浏览次数:20573 次

关于共享内存的请教高手来哦
不知道咋了 共享内存写不进去 说是出错了:
Segmentation fault


下面的是我的代码 请帮我看看啊:
C/C++ code
/***** write.cpp *******/
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>

#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;

typedef struct{
    char name[4];
    int age;
    char d[4];
    int z;
} people;
int main()
{
    int shm_id,i;
    int key;
    char temp;
    people *p_map;
    char *name = (char*)"/home";
    key = ftok(name,0);
    if(key==-1)
        perror("ftok error");

    shm_id=shmget(key,1024,IPC_CREAT);//创建一个内存为1024个字节的共享内存

    if(shm_id==-1)
    {
        perror("shmget error");
        return 1;
    }
    p_map=(people*)shmat(shm_id,NULL,0);

    temp='a';

    for(i = 0;i<10;i++)//可能是这里错了,那又是为什么呢?编译没错的。。。。。。。。。。。。。。。。。
    {
        temp+=1;
        memcpy((*(p_map+i)).name,&temp,1);
        (*(p_map+i)).age=20+i;
        (*(p_map+i)).z = i;
        memcpy((*(p_map+i)).d,&temp,1);
    }
    if(shmdt(p_map)==-1)
        perror(" detach error ");
    return 1;
}



------解决方案--------------------
gdb调试啊


[rob@sdc HS]$ gcc -g test.c
[rob@sdc HS]$ gdb a.out
GNU gdb Red Hat Linux (6.3.0.0-1.153.el4rh)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/tls/libthread_db.so.1".

(gdb) b
No default breakpoint address now.
(gdb) b main
Breakpoint 1 at 0x804848c: file test.c, line 24.
(gdb) r
Starting program: /data/r63905/HuaShan_3780/a.out

Breakpoint 1, main () at test.c:24
24 char *name = (char*)"/home";
(gdb) s
25 key = ftok(name,0);
(gdb) s
26 if(key==-1)
(gdb) s
29 shm_id=shmget(key,1024,IPC_CREAT);//
(gdb) s
31 if(shm_id==-1)
(gdb) s
36 p_map=(people*)shmat(shm_id,NULL,0);
(gdb) s
38 temp='a';
(gdb) s
40 for(i = 0;i<10;i++)//
(gdb) s
42 temp+=1;
(gdb) s
43 memcpy((*(p_map+i)).name,&temp,1);
(gdb) s

Program received signal SIGSEGV, Segmentation fault.
0x004aa0e5 in memcpy () from /lib/tls/libc.so.6


问题定位到了。。。。。。

------解决方案--------------------
p_map可能是0
------解决方案--------------------
友情up