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

新手_段错误,指针的问题,没明白!
C/C++ code
  1 #include <sys/types.h>
  2 #include <sys/ipc.h>
  3 #include <stdio.h>
  4 #include <errno.h>
  5 #include <sys/shm.h>
  6 #include <stdlib.h>
  7 #include <string.h>
  8 #include <time.h>
  9 
 10 typedef struct{
 11         char name[4];
 12         int age;
 13 }people;
 14 
 15 int main(int argc,char *argv[])
 16 {
 17         int shm_id;
 18         key_t key;
 19         people *p_map;
 20         time_t seed = time(NULL);
 21         srand((int)seed);
 22         key = rand();
 23 
 24         shm_id=shmget(key,4096,IPC_CREAT);
 25         p_map=(people*)shmat(shm_id,NULL,0);
 26         (*p_map).age=20;
 27         (*(p_map+1)).age=21;
 28         return 0;
 29 }
 30 
 31 




第26、27行“段错误”,为什么不行啊???

------解决方案--------------------
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <errno.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

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

int main(int argc,char *argv[])
{
int shm_id;
key_t key;
people *p_map;
time_t seed = time(NULL);
srand((int)seed);
key = rand();

shm_id=shmget(key,4096,IPC_CREAT);
p_map=(people*)shmat(shm_id,NULL,0);
(*p_map).age=20;
(*(p_map+1)).age=21;
(*(p_map+2)).age=22;

printf("%d\n", (p_map)->age);
printf("%d\n", (p_map+1)->age);
printf("%d\n", (p_map+2)->age);

return 0;
}

输出:

20
21
22

程序运行正常,没段错误;
------解决方案--------------------
shm_id=shmget(key,4096,IPC_CREAT);
这里有问题,你没有加权限,所以shmat映射的时候失败了,改成
shm_id=shmget(key,4096,IPC_CREAT|0666);就行了

------解决方案--------------------
同意koutatu,我是在root权限下运行的
------解决方案--------------------
探讨

shm_id=shmget(key,4096,IPC_CREAT);
这里有问题,你没有加权限,所以shmat映射的时候失败了,改成
shm_id=shmget(key,4096,IPC_CREAT|0666);就行了