Reputation: 1478
I have this code:
#include<stdio.h>
#include<stdlib.h>
char *K2G(int k)
{
static char g[10];
if (k > 1048576) {
sprintf(g, "%.2fGB", (float) k / 1048576);
} else {
if (k > 1024) {
sprintf(g, "%.2fMB", (float) k / 1024);
} else {
sprintf(g, "%dKB", k);
}
}
printf("%s\n", g);
return g;
}
main()
{
FILE *fp;
int imt = 0, imf = 0, imu = 0;
char cmt[40], cmf[40], cmti[20], cmfi[20], a[20], b[20];
while (1) {
system("clear");
fp = fopen("/proc/meminfo", "r");
fgets(cmt, 40, fp);
fgets(cmf, 40, fp);
fclose(fp);
printf("%s%s\n", cmf, cmt);
sscanf(cmt, "%s%d%s", a, &imt, b);
sscanf(cmf, "%s%d%s", a, &imf, b);
imu = imt - imf;
printf("%s/%s=%d%\n", K2G(imu), K2G(imt), imu * 100 / imt);
sleep(1);
}
}
The output I get is something like:
MemFree: 494256 kB
MemTotal: 10258000 kB
9.78GB
9.31GB
9.31GB/9.31GB=95%
The last line always displays the same two values before the equal sign. The output should have been:
MemFree: 494724 kB
MemTotal: 10258000 kB
9.31GB
9.78GB
9.31GB/9.78GB=95%
Why do I get duplicate values when I call function K2G with printf? This is the line giving me the incorrect results:
printf("%s/%s=%d%\n", K2G(imu), K2G(imt), imu * 100 / imt);
Upvotes: 0
Views: 78
Reputation: 50778
This behaviour is normal, you return a pointer to g
which is a static buffer, and on each call this buffer will be overwritten.
So if you do printf(..., K2G(x), K2G(Y),...)
, the parameters "seen" by printf will both be the same g
buffer with it's latest content.
You can do this:
char simu[20];
char simt[20];
strcpy(simu, K2G(imu));
strcpy(simt, K2G(imt));
printf(..., simu, simt,...);
EDIT:
Or you can use another pattern where you have to provide a buffer to K2G:
char *K2G(int k, char *g)
{
if (k > 1048576) {
sprintf(g, "%.2fGB", (float) k / 1048576);
} else {
if (k > 1024) {
sprintf(g, "%.2fMB", (float) k / 1024);
} else {
sprintf(g, "%dKB", k);
}
}
printf("%s\n", g);
return g;
}
...
char simu[20];
char simt[20];
K2G(imu, simu);
K2G(imt, simt);
printf(..., simu, simt,...);
This is more transparent and avoids the usage of strcpy
.
Upvotes: 2