Thread: SIGSEGV with strcpy and shared memroy

  1. #1
    Registered User
    Join Date
    Mar 2008

    SIGSEGV with strcpy and shared memroy

    Hi All,

    I am trying to read from the file and then copy to the shared memory.

    While doing strcpy i get SIGSEGV.

    Can any body can help here like what is the root cuase of the issue?

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    int main(int argc,char *argv[])
      int k,shmid;
      void *data;
      FILE *fp;
      char *ptr;
      ptr = calloc(20,1);
      shmid=shmget(k, 1000, 0);
      fp = fopen(argv[1],"r");
      strcpy((char *)data,ptr);

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > memset(ptr,20,0);
    1, the arguments are in the wrong order.
    2, it's pointless anyway, since you called calloc to begin with.

    > shmid=shmget(k, 1000, 0);
    Always (repeat - ALWAYS) check for success when you call functions.
    For example, don't you need IPC_CREATE (at least) as a flag?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2015
    You need to check the return values of the functions. Doing so shows that shmat is failing due to permissions.

    This is because you didn't pass any permissions to shmget. Something like:
    shmid=shmget(k, 1000, IPC_CREAT | 0666);
    From the terminal, type ipcs -m and look for a shared memory segment with 1000 bytes. This is the segment you created; it isn't deleted when the program exits. Note the perms; 0 means no access permission at all.

    Note the shmid and type ipcrm shm 12345 (where 12345 is the shmid you noted). This deletes the resource so you can create it anew with proper permissions.

  4. #4
    Registered User
    Join Date
    Mar 2008
    Thanks salem and algorism.

    I just overlooked the creation part of the shm.Its actually like reader would create and wirter would use it.
    In this case i was runing writer first. So no creation of the shm at all..

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. SIGSEGV fault
    By i_wanna_rokk in forum C Programming
    Replies: 2
    Last Post: 05-03-2013, 01:31 PM
  2. Shared Memroy Indroduction Program
    By booter in forum C Programming
    Replies: 3
    Last Post: 09-20-2011, 05:27 PM
  3. SIGSEGV hell
    By morbidslug in forum C++ Programming
    Replies: 6
    Last Post: 11-15-2010, 10:00 AM
  4. Replies: 1
    Last Post: 06-19-2010, 07:42 AM
  5. SigSegv Violation
    By Mellowz in forum C Programming
    Replies: 3
    Last Post: 02-23-2005, 03:06 AM

Tags for this Thread