Search code examples
cserializationprintfansi-c

use sprintf with char *


Im trying to use this but when I run it with valgrind I have some memory problems.

For expample

char *serialize_file(t_file_package *pack) {

     char *payLoad = malloc(numDigits(pack->file_desc)+numDigits(pack->priority)+strlen(pack->code)+2);
     sprintf(payLoad, "%d#%d#%s", (uint32_t)pack->file_desc,(int16_t)pack->priority, pack->code);
     char *pack = malloc(numDigits(PROCESS) + numDigits((int64_t)strlen(payLoad)) + strlen(payLoad)+2);

     sprintf(pack, "%d#%d#%s",PROCESS, strlen(payLoad), payLoad);
     free(payLoad);
     return pack;
}

I know of the existence of asprintf but I downt know why i cant use it in my GNU ANSI C project... My eclipse says that that function is not recognized

Thank you in advanced!


Solution

  • you aren't allowing space for the null character at the end of the string - the string needs space for the digits in "file_desc", the digits in "priority", the characters in "code", the two "#" characters and the terminal null character.

    The same problem exists with the second call to malloc