+ -
当前位置:首页 → 问答吧 → memcpy产生的segment fault, 怎么改?

memcpy产生的segment fault, 怎么改?

时间:2010-08-18

来源:互联网

源程序如下:
linux下运行,memcpy(*(p_map+i).name, &temp, 1) 会产生segment fault, 怎么解决?

/***** testwrite.c *******/
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>

typedef struct{
        char name[4];
        int age;
} people;

main(int argc, char** argv)
{
        int shm_id,i;
        key_t key;
        char temp;
        people *p_map;
        char* name = "/dev/shm/myshm2";
        key = ftok(name,0);
        if(key==-1)
                perror("ftok error");
        shm_id=shmget(key,4096,IPC_CREAT);       
        if(shm_id==-1)
        {
                perror("shmget error");
                return;
        }
        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;
        }
        if(shmdt(p_map)==-1)
                perror(" detach error ");
}

作者: keneth2078   发布时间: 2010-08-18

  1. memcpy(*(p_map+i).name, &temp, 1)
复制代码
===>
注意优先级, . 的优先级比*高
  1. memcpy((*(p_map+i)).name, &temp, 1);
复制代码

作者: churchmice   发布时间: 2010-08-18



QUOTE:
===>
注意优先级, . 的优先级比*高
churchmice 发表于 2010-08-18 18:27



   
   兄台, 这样仍然不行啊。。。。

作者: keneth2078   发布时间: 2010-08-18