A. Ingrosso A. Ingrosso - 9 months ago 23
C Question

function does not return value in c

I have a behaviour that I don't understand.
When I call function get_bloccante_multimsg(...) doesn't return anything, read_m variable is not valorised and the next instruction is not executed.

The code below is a subpart of the program, hope that is helpful to identify the problem.

buffer.h

msg_t* get_bloccante_multimsg(int buffer, int C_id, int semid, const int N);


buffer.c

msg_t* get_bloccante_multimsg(int buffer, int C_id, int semid, const int N)
{
char* string;
char* shared_memory;
int *Cindex;

struct shmid_ds shmbuffer;

sb.sem_num = PIENE;
sb.sem_op = -1;
sb.sem_flg = 0;
if (semop(semid, &sb, 1) == -1) {
perror("semop() consumatore P(PIENE)");
exit(-9);
}

sb.sem_num = USO_T;
sb.sem_op = -1;
sb.sem_flg = 0;
if (semop(semid, &sb, 1) == -1) {
perror("semop() consumatore P(USO_T)");
exit(-9);
}

Cindex = shmat(C_id, NULL, 0);
shmctl(buffer, IPC_STAT, &shmbuffer);
shared_memory = (char *) shmat(buffer, (void *)0, 0);
memcpy(string, &shared_memory[*Cindex*20], 20);
*Cindex = (*Cindex + 1) % N;
shmdt(Cindex);
shmdt(shared_memory);

sb.sem_num = USO_T;
sb.sem_op = 1;
sb.sem_flg = 0;
if (semop(semid, &sb, 1) == -1) {
perror("semop() consumatore V(USO_T)");
exit(-9);
}

sb.sem_num = VUOTE;
sb.sem_op = 1;
sb.sem_flg = 0;
if (semop(semid, &sb, 1) == -1) {
perror("semop() consumatore V(VUOTE)");
exit(-9);
}

return msg_init_string(string);
}


main.c

msg_t *read_m;

for (int i = 0; i < C; i++)
{
// fork consumatore
cons_pid[i] = fork();
switch(cons_pid[i]) {
case -1: // fork fallita
exit(-5);
break;
case 0:
read_m = get_bloccante_multimsg(segment_id, C_id, semid, N);
printf("Messaggio in array: %s", (char *)getMessage(read_m));
exit(0);
break;
default:
break;
}
}


Thanks for your help.

Answer Source

In the function get_bloccante_multimsg(), the pointer to char string is used uninitialized in the line:

memcpy(string, &shared_memory[*Cindex*20], 20);

and later at:

return msg_init_string(string);

This leads to undefined behavior. You need to allocate space for the string and assign the address to string.