segmentation fault with shared memory #2

  • Follow


hi everybody
i ve a pb with this code
    #include <stdio.h>
    #include <stdlib.h> 
    #include <string.h> 
    #include <sys/types.h> 
    #include <sys/ipc.h> 
    #include <sys/shm.h> 

    #define SHM_SIZE 4096  /* make it a 4K shared memory segment */

    int main()
    { 
        key_t key,key_flag;
        int shmid,id_flag;
        char *data,*message;
        int mode,*flag,c;


        /* make the key: */ 
        if ((key_flag = ftok("shm.c", 'A')) == -1) {
            perror("ftok");
            exit(1);
        } 
 if ((id_flag= shmget(key_flag,sizeof(int), 0644 | IPC_CREAT)) == -1) {
            perror("shmget");
            exit(1);
        }
 flag =(int*) shmat(id_flag, NULL, 0);
        if (flag ==(int*) -1) {
            perror("shmat");
            exit(1);
        }
  printf("quel est votre choix \n");
     scanf("%d",&c);
     (*flag)=c;
            printf("le drapeau ecrit dans le segment a pour numero: \"%d\"\n",c);


 switch(c)
 {
 case 1:
  printf("demande d'�tablissement d'une connexion\n");
  break;
 case 2:
  printf("demande d'ouverture de session\n");
  break;
 case 3:
  printf("demande d'envoi de message  \n");

   {if ((key = ftok("shm.c", 'R')) == -1) {
             perror("ftok");
             exit(1);
          }

          /* connect to (and possibly create) the segment: */
     if ((shmid = shmget(key,SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
             perror("shmget");
             exit(1);
         }

         /* attach to the segment to get a pointer to it: */
         data =(char*) shmat(shmid, NULL, 0);
         if (data == (char*)-1) {
             perror("shmat");
             exit(1);
          }

         /* modify the segment */

      printf("entrez ici votre message \n");
   fflush(stdin);
       fgets(message,sizeof(message),stdin);
             printf("message ecrit dans le segment: \"%s\"\n",message);
      strncpy(data, message,SHM_SIZE);


         /* detach from the segment: */
         if (shmdt((char*)data) == -1) {
             perror("shmdt1");
             exit(1);
         }

  break;
  }
 default:
  break;
 }
  if (shmdt(flag) == -1) {
            perror("shmdt2");
            exit(1);
        }

        return 0; 
    } 
in fact where c ==3
i obtain segmentation fault before i even enter the message
and i don't see why 
any ideas !!
thanks a lot
0
Reply naourez_m 8/17/2004 7:38:10 PM


0 Replies
496 Views

(page loaded in 0.021 seconds)

Similiar Articles:













7/23/2012 9:18:19 AM


Reply: