Pergunta

I am trying to create an array of structs that is shared between a parent and child processes. I am getting a segmentation fault when trying to access the array data.

I feel certain that the problem has something to do with the way I'm using pointers, as this is an area I'm not very comfortable with.

Please note that I edited out most of the code that didn't seem relevant.

/* structure of Registration Table */
struct registrationTable{
    int port;
    char name[MAXNAME];
    int req_no;
};

main() {

    /* the registrationTable is to be a shared memory space with each child
    process able to access and update. No concurrency controls are 
     implemented. The parent process is responsible for cleaning up after
     the kiddies.
 */
struct registrationTable base_table[REG_TABLE_SIZE];
for (int i = 0; i < REG_TABLE_SIZE; i++) {
    base_table[i].req_no = 0;
    memset(base_table[i].name, '\0', MAXNAME);
    base_table[i].port = 0;
}

printf("\nMapping Shared Memory\n");

//set up shared memory space
//void *mmap(void *addr, size_t length, int prot, int flags,
    //              int fd, off_t offset);
//      addr = NONE, prot = PROT_NONE, flags = MAP_SHARED 
struct registrationTable *table = mmap(base_table, sizeof(base_table),
                        PROT_READ | PROT_WRITE, 
                        MAP_SHARED | MAP_ANONYMOUS,
                        -1, 0);

while(1){
    pid_t child = fork();

    if (child == 0) {//is child

        for(int i = 0; i < REG_TABLE_SIZE; i++) {

            printf("\nExamining table looking for client at %s port: %d\n", 
                    packet_reg.data, clientAddr.sin_port);

            printf("\ntable[1].req_no: %d", ta[i].req_no);

                            //segmentation fault on next line
            if (strcmp(table[i].name, packet_reg.data) == 0 
                    && table[i].port == clientAddr.sin_port) {
                table[i].req_no++;
}
Foi útil?

Solução

You haven't initialized content of the table after it was allocated by mmap. So it contains garbage. And so strcmp(table[i].name, packet_reg.data) has a great chance to go over allocated buffers and access e.g. non-allocated memory.

  1. initialize table properly;
  2. use strncmp for the comparison there.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top