免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1864 | 回复: 2
打印 上一主题 下一主题

memset 对于 普通内存和共享内存的区别~ [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-08-21 14:09 |只看该作者 |倒序浏览

  1. #define SIZE 10000
  2. #define MODE 0600 /*r/w*/
  3. #define NUM 10


  4. #include<stdio.h>
  5. #include<stdlib.h>
  6. #include<sys/ipc.h>
  7. #include<sys/shm.h>
  8. #include<sys/types.h>
  9. #include<string.h>

  10. //#include

  11. struct student{
  12.         char name[20];
  13.         int age;
  14. };

  15. int main(){
  16.         int shmid;
  17.         struct student *ptr;
  18.         struct student *student_array=ptr;

  19.         int i=0;
  20.         if((shmid=shmget(IPC_PRIVATE,SIZE,MODE))<0){
  21.                 printf("1.error\n");
  22.                 exit(-1);
  23.         }

  24.         if ((ptr=(struct student*)shmat(shmid,0,0))==(void*)-1){
  25.                 printf("2.error\n");
  26.                 exit(-1);
  27.         }
  28.        memset(ptr,0,SIZE);
  29.         printf("sizeof(struct student):%d:%x\n",sizeof(struct student));
  30.         for(i=0;i<NUM;i++){

  31.                 printf("%lx\n",student_array+i);
  32.                 memcpy(student_array[i].name,"LuYuan",6);///用于测试所以就写6,
  33.                 student_array[i].age=i;
  34.         }
  35.         for(i=0;i<NUM;i++){
  36.                  printf("name=%s\n",student_array[i].name);//这行的输出会有乱码
  37.                  printf("age=%d\n",student_array[i].age);

  38.         }

  39. }
复制代码


这个程序输出会有乱码。

我想问的是既然我都已经给共享内存初始化为0了,怎么可能会有乱码呢,


试验环境是
linux 2。6。15
gcc version 4。0。3

论坛徽章:
1
2015年辞旧岁徽章
日期:2015-03-03 16:54:15
2 [报告]
发表于 2006-08-21 14:22 |只看该作者
你这个程序有两个错误。
严重的错误:
printf("sizeof(struct student):%d:%x\n",sizeof(struct student));
你只给了 printf 一个参数,但是格式化串里却要求输出两个参数。
致命错误:
struct student *student_array=ptr;
ptr 此时尚未赋值,其值未定义。
因此 student_array 的值也是未定义值———它并没有指向共享内存。

论坛徽章:
0
3 [报告]
发表于 2006-08-21 15:09 |只看该作者
考 晕了。。。。。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP