Reputation: 5122
In C, I have this function here:
// Returns human friendly byte amount
char *byteconvert(unsigned long b_) {
float b = (float) b_;
int n = 0;
while (b / 1000 >= 1) {
b /= 1000;
n++;
}
char *buffer = malloc(32);
sprintf(buffer, "%.2f%c", b, "BKMGT"[n]);
return buffer;
}
Do I just assign a variable to this function call and then free it later? What if I want to just print it, something like this:
int x = 123456;
printf("Size: %s\n", byteconvert(x));
How can I do this without memory leak? This seems like a basic question in C, and I just don't know the correct way to go about this.
I found many posts similar to this online, but none of them had a definite or good solution.
Upvotes: 2
Views: 66
Reputation: 141658
If you don't want to rely on the caller doing free
then have the caller pass in the buffer in the first place.
Also you should check n < 5
before using it as array index.
void byteconvert(unsigned long b_, char *buf, size_t buf_len )
{
...
snprintf(buf, buf_len, "%.2f%c", .....
}
Upvotes: 1
Reputation: 27240
How can I do this without memory leak?
you need to free the memory after use.
int x = 123456;
char * temp = NULL;
temp = byteconvert(x);
printf("Size: %s\n", temp);
//after use just free it
free(temp);
Upvotes: 0
Reputation: 16126
Your intuition is correct. Store the pointer returned by byteconvert()
in a variable, and free it when it is no longer needed.
Upvotes: 0