简体   繁体   English

函数不返回c中的值

[英]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. 当我调用函数get_bloccante_multimsg(...)时不返回任何内容时,read_m变量将不被赋值,并且下一条指令也不会执行。

The code below is a subpart of the program, hope that is helpful to identify the problem. 下面的代码是该程序的子部分,希望有助于识别问题。

buffer.h buffer.h

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

buffer.c 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 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. 谢谢你的帮助。

In the function get_bloccante_multimsg() , the pointer to char string is used uninitialized in the line: 在函数get_bloccante_multimsg() ,在行中未初始化的情况下使用了指向char string的指针:

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 . 您需要为字符串分配空间,并将地址分配给string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM