Home > Software engineering >  Memcpy failing to copy from stream to float variable
Memcpy failing to copy from stream to float variable

Time:05-03

Im trying to send a struct through a socket, for this, im serializing and deserializing it

typedef struct pcb{
    uint16_t  id;
    uint16_t  tamano;
    uint8_t   pc;
    int       tp;       
    float     srt;
}t_pcb;

My problem comes when trying to rebuild the struct, specifically when trying to store the float value.

static void deserializar_header_PCB_KTC(void* stream, t_pcb* pcb, uint8_t *tamanoInstrucciones) {
    int offset = 0;


    memcpy(pcb->id, stream, sizeof(uint16_t));
    offset = sizeof(uint16_t);
    memcpy(pcb->tamano, stream offset, sizeof(uint16_t));
    offset  = sizeof(uint16_t);
    memcpy(pcb->pc, stream offset, sizeof(uint8_t));
    offset  = sizeof(uint8_t);
    memcpy(pcb->tp, stream offset, sizeof(int));
    offset  = sizeof(int);
    memcpy(pcb->srt,stream offset, sizeof(float)); 
    offset  = sizeof(float);
    memcpy(tamanoInstrucciones, stream offset, sizeof(int));

    
}

the following error comes up:

src/protocolo.c:323:12: error: incompatible type for argument 1 of ‘memcpy’
     memcpy(f, stream offset, sizeof(float)); 

i already tested the communication using int type instead of float and it works properly. I considered multiplying the float value and use int type, but i would lose definition so im trying to find some other way.

if anyone could help me with this i would really appreciate it.

Serialization

static void* serializar_header_PCB_KTC(t_pcb* pcb) {
    void* stream = malloc(sizeof(op)   sizeof(int)   sizeof(uint16_t) * 2   sizeof(uint8_t) * 2   sizeof(float));
    void* pos    = stream;
    uint8_t tamanoInstrucciones = tamano_intrucciones_pcb(pcb);
    
    op cop = HEADER;

    memcpy(pos, &cop, sizeof(op));
    pos  = sizeof(op);
    memcpy(pos, &pcb->id, sizeof(uint16_t));
    pos  = sizeof(uint16_t);
    memcpy(pos, &pcb->tamano, sizeof(uint16_t));
    pos  = sizeof(uint16_t);
    memcpy(pos, &pcb->pc, sizeof(uint8_t));
    pos  = sizeof(uint8_t);
    memcpy(pos, &pcb->tp, sizeof(int));
    pos  = sizeof(int);
    memcpy(pos, &pcb->srt, sizeof(float));
    pos  = sizeof(float);
    memcpy(pos, &tamanoInstrucciones, sizeof(uint8_t));
    return stream;
}

CodePudding user response:

Always use the adresses of the objects with memcpy. You are using the value and you need to send the pointer.. for example:

memcpy(&pcb->srt,stream offset, sizeof(float)); 
  • Related