Thread: memcpy into shm resulting in segfault?

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    3

    Cool memcpy into shm resulting in segfault?

    Code:
    #include <stdio.h>#include <semaphore.h>
    #include <unistd.h>
    #include <readline/readline.h>
    #include <readline/history.h>
    #include <stdlib.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <sys/mman.h>
    #include "tlpi_hdr.h"
    #include "error_functions.h"
    //DECLARE GLOBAL VARIABLES/ARRAYS
    FILE *fp;
    int *address;
    //DEFINE POTIONS
    
    
    typedef struct potion{
    char *name;
    int count;
    } potion;
    
    
    
    //DEFINE MORE GLOBAL VARIABLES/ARRAYS
    potion all_potions[1000];
    //ERROR CHECKING FOR SHAREMEMORY
    static void usageError(const char *progName)
    {
    fprintf(stderr, "Usage: %s [-cx] name size [octal-perms]\n", progName);
    fprintf(stderr,"    -c     Create shared memory (O_CREAT)\n");
    fprintf(stderr, "   -x     Create exclusively (O_EXCL)\n");
    exit(EXIT_FAILURE);
    }
    //READ FILE FUNCTION
    void readFile(){
    	 char temp_name[200];
    	 char str[200];
    	 if((fp = fopen("inventory_input.txt", "r")) == NULL){
                    printf("Cannot open inventory_input.txt file.\n");
                    exit(1);
    
    
            } else {
    		while(! feof(fp)){
    			fscanf(fp,"%s",str);
    			int *lines_left = malloc(sizeof(int));
    			int *lines_count = malloc(sizeof(int));
    			*lines_left = atoi(str);
    			*lines_count = 0;
    			while(*lines_left>0){
    				
    			//	printf("%d lines left\n",*lines_left);
    				
    				fscanf(fp, "%s",temp_name);
    				all_potions[*lines_count].name = (char *)malloc(100);
    				strcpy(all_potions[*lines_count].name,temp_name);
    				fscanf(fp, "%s",str);
    				all_potions[*lines_count].count = atoi(str);
    				printf("%s: %s left\n",temp_name,str);
    				*lines_left=*lines_left-1;
    				*lines_count=*lines_count+1;
    			}
    			break;	
    		}
    	}
    	
    
    
    }
    //MAIN FUNCTION
    int main(int argc, char* argv[]){
    	int opt, fd, flags;
    	mode_t perms;
    	size_t size;
    	void *addr;
    	size=sizeof(potion)*1000;
    
    
    	
    		fd = shm_open("butt",O_CREAT,0);
    //CONDITIONAL FOR SHARE MEM
    		printf("Resized to %ld bytes\n", (long) size);
    		addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    
    
    
    
    	system("pause");
    	getchar();
    	readFile();
    	memcpy(addr, all_potions, size);	
    	shm_unlink("butt");
    	exit(EXIT_SUCCESS);
    	return 0;
    }
    So in my main function, I'm trying to create a shared memory space to store an array of potions. I have defined potions in typedef format above.

    I figured size=sizeOf(potion)*1000 would allow 1000 potions.

    When I do the memcpy into the shm, however (I have checked, and the instantiation of it works as shows up in /dev/shm)

    It just seg faults, no matter what.

    I'm new to all of this and my professor is unavailable for the week and we're allowed to research. Any suggestions? Am i not allocating enough? Are my memcpy parameters wrong?

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    There are so many errors in your code it makes my head spin.

    Most bizarely, why are you mallocing single ints into lines_left and lines_count? What's wrong with plain old ints? And you're doing it again and again in the loop, without ever freeing them.

    You're not checking for end-of-file correctly in readFile.
    And you don't close the file.

    You're using global variables for no apparent reason.

    Why do you have an exit before main's return? There's no point. Just return 0 or, equivalently, return EXIT_SUCCESS.

    And you're not checking the return value of mmap. It returns MAP_FAILED on failure.

    If it's failing, try a non-zero mode on shm_open, like S_IRWXU.

    You may encounter other problems even if the shared memory works!
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Registered User
    Join Date
    Oct 2013
    Posts
    3
    Quote Originally Posted by oogabooga View Post
    There are so many errors in your code it makes my head spin.

    Most bizarely, why are you mallocing single ints into lines_left and lines_count? What's wrong with plain old ints? And you're doing it again and again in the loop, without ever freeing them.

    You're not checking for end-of-file correctly in readFile.
    And you don't close the file.

    You're using global variables for no apparent reason.

    Why do you have an exit before main's return? There's no point. Just return 0 or, equivalently, return EXIT_SUCCESS.

    And you're not checking the return value of mmap. It returns MAP_FAILED on failure.

    If it's failing, try a non-zero mode on shm_open, like S_IRWXU.

    You may encounter other problems even if the shared memory works!

    Thanks. I will do those things.

    This is a result of my university completely and utterly failing to teach us C. They never taught us C. Only Java, Python, and PHP. C++ for 1 class.

    I'm using global variables because the other ........ing functions need to be able to access the potions array.

    I'm sorry and I know i'm an awful human being.
    Last edited by 0xa0d933h52; 10-08-2013 at 08:49 PM.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > char *name;
    and
    > all_potions[*lines_count].name = (char *)malloc(100);
    and
    > memcpy(addr, all_potions, size);

    When you've copied your pointers into shared memory, they become meaningless.

    Try it with char name[100] and forego the malloc in the file reader.
    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.

  5. #5
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Quote Originally Posted by 0xa0d933h52 View Post
    I'm using global variables because the other ........ing functions need to be able to access the potions array.
    I'm sorry and I know i'm an awful human being.
    It's best not to be emotional about these things. I wasn't attacking you personally. I simply have no tact. C'est la vie. And obviously I wouldn't have said the globals were suboptimal if they were necessary to achieve your goal.

    Besides mallocing the single ints (which I've never seen before so it took me by surprise), your main problem is not checking the return values of functions for error conditions. If you did you'd have seen that mmap was failing, although it may not be obvious why. I'm suggesting it's because you're not setting access permissions in the shm_open call.

    Also, Salem has made explicit my hint at further problems, which is that the pointers to the malloced potion names will not work in the shared memory. The simplest solution is to do as Salem says and statically allocate space in your potion structure.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  6. #6
    Registered User
    Join Date
    Oct 2013
    Posts
    3
    Quote Originally Posted by Salem View Post
    > char *name;
    and
    > all_potions[*lines_count].name = (char *)malloc(100);
    and
    > memcpy(addr, all_potions, size);

    When you've copied your pointers into shared memory, they become meaningless.

    Try it with char name[100] and forego the malloc in the file reader.
    Thank you Salem

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc() resulting in a SegFault?!
    By cipher82 in forum C++ Programming
    Replies: 21
    Last Post: 09-18-2008, 11:24 AM
  2. memcpy
    By m37h0d in forum C++ Programming
    Replies: 28
    Last Post: 04-12-2008, 09:10 PM
  3. memcpy
    By mbooka in forum C Programming
    Replies: 10
    Last Post: 02-28-2006, 02:25 AM
  4. Utter confusion, resulting from SYSTEMTIME
    By Tronic in forum Windows Programming
    Replies: 8
    Last Post: 01-04-2005, 08:21 PM
  5. Function call resulting in a strange looping
    By cineplex in forum C++ Programming
    Replies: 4
    Last Post: 02-02-2003, 02:01 PM

Tags for this Thread