Question

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.

Was it helpful?

Solution 2

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);

OTHER TIPS

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", .....
}

Your intuition is correct. Store the pointer returned by byteconvert() in a variable, and free it when it is no longer needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top