Modify const void * in C (SSL_read) [closed]

1

I have the following function:

   int SSL_read(SSL *ssl, void *buf, int num);

And I would like to modify the buf (Modify the Header), I have tried several ways but the program always hangs or simply does not work.

(The function is openssl )

    
asked by Mr Jhon 03.01.2017 в 18:19
source

2 answers

2
  

I would like to change the buffer

Then it's not const .

  

the program hangs or simply does not work

It looks like a clear description of undefined behavior . I bet that to write in buffer you had to do a constant pointer conversion to non-constant pointer; this can cause undefined behavior, try passing the buffer as not constant:

int mifuncion(void * buffer){
     /* mas codigo */
}

Another thing that could be happening (and that would also cause indefinite behavior) is that you screw up writing in buffer , I see that mifuncion does not receive size parameter so if you are passing a pointing pointer to a buffer of size X but you write Y (if Y> X) you could have this problem, to solve it it indicates what the writing limit is:

int mifuncion(void * buffer, int tamanyo_buffer){
     /* mas codigo */
}

And use the tamanyo_buffer parameter to write a maximum of that number of bytes.

But that does not help either, because the type void has no size and consequently you can not do pointer arithmetic with it, so I bet that in addition to transforming bufer so that it is not constant, you must transform it to a guy with size

int mifuncion(void * buffer, int tamanyo_buffer){
    char *inicio = (char *)buffer;
    /* mas codigo usando inicio en lugar de buffer */
}
    
answered by 04.01.2017 в 09:46
1

Your crash program is probably because you are passing a string literal to your function:

mifuncion("hola");

The hola string is stored in the constant memory region of the program, which is a region of your executable protected by the operating system as read-only. If anything that comes from that region tries to be modified, crash. Hence, castings to remove const from something are so dangerous. They are only safe if you know the origin of the data received (and a free function should never know).

Your only solution is that the function receives the string as not constant, and if you need to pass a constant string (a string literal), first make a copy.

char buff[espacio_suficiente];
// copiar hola en buff con strcpy o memcpy

mifuncion(buff);
    
answered by 04.01.2017 в 16:43