Search code examples
cipcmmap

storing strings in a mmap shared array? (C)


I am trying to store all filenames in the current directory in a shared array using mmap I can print all 9 files in the directory to the screen but when I try to store them in the array (shared_array) and print the array, all entries contain the same string (file.txt). Thanks in advance!

char **shared_array; 
shared_array= mmap(0,100*sizeof(char*),PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON,-1,0);  
char * filename;

const MAXLINE = 80; 
char line [MAXLINE];

FILE *fp = popen("/bin/ls","r");

int i = 0; 
while(fgets(line, MAXLINE,fp) !=NULL){    
    filename = line;
    shared_array[i] = filename; 
    i++;        
}
pclose(fp);

int j;
for(j=0;j<i;j++){
    printf("\n%s",shared_array[j]);
}

Solution

  • When you do this:

    filename = line;
    shared_array[i] = filename; 
    

    You're not actually copying the contents of your line array to shared_array. You're assigning the address of line to each array element. As a result, all array elements point to the same place, i.e. line, which will only contain the most recently stored value.

    You need to allocate memory for each string you want to copy. You could do that with strdup:

    shared_array[i] = strdup(line);
    

    But the problem with this is that you have shared memory containing pointers to non-shared memory.

    You'll need to allocate space in shared memory for an array of strings:

    const MAXLINE = 80;
    char (*shared_array)[MAXLINE]; 
    shared_array= mmap(0,100*MAXLINE,PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON,-1,0);
    

    Then you can use strcpy to copy into each array element:

    strcpy(shared_array[i], line);