Home > other >  Passing buffer to function for writing
Passing buffer to function for writing

Time:08-13

I'm trying to implement a quick prototype program to prepare a message that I intend to use as a tcp socket communication protocol. I'm new at this, and I can't quite understand why running the following prints (null). Am I failing at passing the pointer to the subroutine?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char *header = "testhd";

void pack_message(char *body, char *buffer)
{
    size_t body_size, msg_size, buffer_size;
    char hex_size[11];
    
    body_size = strlen(body);
    snprintf(hex_size, 11, "0x%x", body_size);
    msg_size = 16   body_size;
    buffer_size = msg_size   1;
    
    if (!buffer){
        buffer = malloc(buffer_size);
    }else{
        buffer = realloc(buffer, buffer_size);
    }
    
    memset(buffer, 0, buffer_size);
    
    strcat(buffer, header);
    strcat(buffer, hex_size);
    strcat(buffer, body);
}

int main(){
    char *buffer = NULL;
    char *body = "testmsg";
    pack_message(body, buffer);
    printf("%s", buffer);
    return 0;
}

CodePudding user response:

Please note that char *buffer in main function and char *buffer in pack_message function are two different pointers which are pointing to the same NULL address. So in Your case functiom pack_message is working with local pointer and that's the reason why running Your code prints null.

To make Your code work You could potentially take an approach where You pass an address of pointer itself as an argument to the pack_message function so main function could look like that:

int main(){
    char *buffer = NULL;
    char *body = "testmsg";
    pack_message(body, &buffer);
    printf("%s", buffer);
    return 0;
}

Your pack_message function should be changed to:

void pack_message(char *body, char **buffer)
{
    size_t body_size, msg_size, buffer_size;
    char hex_size[11];
    
    body_size = strlen(body);
    snprintf(hex_size, 11, "0x%zx", body_size);
    msg_size = 16   body_size;
    buffer_size = msg_size   1;
    
    if (!buffer){
        *buffer = malloc(buffer_size);
    }else{
        *buffer = realloc(*buffer, buffer_size);
    }
    
    memset(*buffer, 0, buffer_size);
    
    strcat(*buffer, header);
    strcat(*buffer, hex_size);
    strcat(*buffer, body);
}

Please note that there I changed also one more potential issue:

snprintf(hex_size, 11, "0x%zx", body_size);

As body_size is of type size_t it is better idea to use %zx as size_t can be different size than unsigned integer, for details on printf please take a look at: https://cplusplus.com/reference/cstdio/printf/

Similar approach can be taken to char *body = "testmsg"; especially when its value will be much longer string. For further improvements I would recommend to redesign pack_message function to return a pointer to allocated buffer as it will lower the chances to forget about freeing memory when not needed anymore.

  • Related