coolerking
coolerking

Reputation: 521

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!

Upvotes: 1

Views: 717

Answers (2)

Nick
Nick

Reputation: 2050

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

Upvotes: 1

xaizek
xaizek

Reputation: 5252

You forgot about trailing null character '\0'. Add one more byte to argument of malloc() calls (replace +2 with +3) and all should be fine.

Upvotes: 1

Related Questions