I have the following code which segfaults, and I have absolutely no clue why. Any help would be very much appreciated.
The segfault happens when I do this (to check whether everything has been correctly initialised). Nothing is printed so it segfaults on the first line. Unfortunately I cannot use valgrind as this code is located within a sandbox which I can’t access, so can’t check the problem there.
for (i = 0 ; i<nb_read ; i++) {
fprintf(stdout, "Read Lock i %d %p \n ",i, nap->read_buffer[i]->sem_handle);
fprintf(stdout, "Write Lock i %d %p \n ",i, nap->write_buffer[i]->sem_handle);
fprintf(stdout, "Read Buffer i %d %p \n ",i, nap->read_buffer[i]->buffer);
fprintf(stdout, "Write Buffer i %d %p \n ",i, nap->write_buffer[i]->buffer);
}
where the SharedStruct is a struct with a char* buffer member and int sem_handle
SharedStruct** create_buffer(int nb, int size) {
SharedStruct** result = malloc(nb * sizeof(SharedStruct*));
int i = 0 ;
for (i = 0 ; i<nb ; i++) {
SharedStruct* res= malloc(nb *sizeof(SharedStruct));
res->buffer = malloc(size * sizeof(char));
int lock = initialise_protection();
fprintf(stdout, "\n Semaphore initialised to %d \n ", lock);
res->sem_handle = lock ;
}
return result ;
}
I don’t see you initializing the pointers contained in result. You just allocated space for them, seems you forgot to do result[i]=res inside your loop.