I get segmentation fault with "shmat" function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • what
    New Member
    • May 2012
    • 2

    I get segmentation fault with "shmat" function

    I want to write in a file called "sharedmem" which is in the same directory that the code, but i get segmentation fault. I think I have found the line of the error, but i dont know how to solve it.
    This is the code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/shm.h>
    #include <errno.h>
    
    long int *seg_part;
    
    void abandon(char message[]){
    	perror(message);
    	exit(EXIT_FAILURE);
    }		
    
    int main(int argc, char **argv){
    	key_t cle;
    	int id, reponse;
    	long int *seg_part;
    
    	if(cle = ftok("sharedmem", 'A') == -1) abandon("ftok");
    	if(id = shmget( cle, sizeof(long int), IPC_CREAT | IPC_EXCL | 0666) == -1)
    		if(errno == EEXIST) abandon("Le segment exist deja");
    		else abandon("shmget");
    
    	if((seg_part = (long int *) shmat(id, NULL, SHM_R | SHM_W)) == NULL)
    		abandon("shmat");
    
    	*seg_part = 0;
    
    	if(shmdt((char*) seg_part) == -1) abandon("shmdt");
    	if(shmctl(id, IPC_RMID, NULL) == -1) abandon("shmctl (remove)");
    	return EXIT_SUCCESS;
    }
    Last edited by Banfa; May 3 '12, 08:35 AM. Reason: Added code tags round the code
  • what
    New Member
    • May 2012
    • 2

    #2
    I forgot to write that the error line is "*seg_part = 0;"

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      shmat returns (void *)-1 on error but you are testing for NULL (0) at line 23. If the function failed your test at line 23 would fail to catch the error condition and then and line 26 you will dereference (long int *)-1 which will almost certain fail in the manor you are observing.

      Comment

      Working...