문제

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.

도움이 되었습니까?

해결책 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);

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top