Вопрос

I have been trying to find out the following problem in the code given below.

#define CONTAINER_LENGTH_OFF 0
#define CONTAINER_TYPE_OFF 4
#define CONTAINER_CODE_OFF 6
#define CONTAINER_TRANSACTION_ID_OFF 8
#define CONTAINER_PAYLOAD_OFF 12

void STRIP_CONTAINER(const char *container, uint16_t *type, uint16_t *code, uint64_t *payload_size, char *payload)
{
    *type = *( (uint16_t*)(container+CONTAINER_TYPE_OFF) );
    *code = *( (uint16_t*)(container+CONTAINER_CODE_OFF) );

    if ( (unsigned int)*(container + CONTAINER_LENGTH_OFF) > 12 )
     payload = container + CONTAINER_PAYLOAD_OFF;
    else
     payload = NULL;

    *payload_size = *( (uint32_t *)(container + CONTAINER_LENGTH_OFF) ) - CONTAINER_SIZE;
 }

int main()
{
   char *container = NULL;
   uint16_t type;
   uint16_t code;
   char *payload = NULL;
   uint64_t payload_size = 0; 
   .....
   .....
   container = malloc(CONTAINER_SIZE + payload_size);
   // memory pointed to by the container is populated with required data by following
   // code which is not shown for simplicity purposes. And also no other variables,
   // declared above, are modified until the function STRIP_CONTAINER() is called below.
   .....
   STRIP_CONTAINER(container, &type, &code, &payload_size, payload);
   .....
}

In the above code, after populating the memory pointed to by the pointer "container" and then calling the function STRIP_CONTAINER(), all the variables passed by address to STRIP_CONTAINER() function seems to get updated as according to the code except for the pointer "payload" which stays 0 even after the assignment (even after the if condition being true). I wonder why this behaviour. Please help me where I am going wrong.

And also please do kindly inform if anymore information is required.

For your information I am using gcc with Eclipse kepler and the inbuilt debugger(hopefully i believe it to be gdb). The above observation is made by the debugger in eclipse.

Это было полезно?

Решение

You have to pass the payload pointer by reference, and de-reference it in your STRIP_CONTAINER function. In your original call, you are passing the value of payload. This means that you are creating a copy of payload in STRIP CONTAINER's call stack and operating on the copy instead of the "original." The copy is lost after STRIP_CONTAINER terminates.

The function header/prototype of STRIP_CONTAINER will instead look like this:

void STRIP_CONTAINER(const char *container, uint16_t *type, uint16_t *code, uint64_t *payload_size, char **payload)

Inside your function, you can de-reference payload normally and operate on it.

Your call can then be modified to:

STRIP_CONTAINER(container, &type, &code, &payload_size, &payload);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top