abuckau907 (04-05-2014)
Hello, This function serves to convert a size of a module for example, string, and shows the size, in bytes, KB, MB, GB, or TB ...
Code:char* BytesToSize( float Bytes ) { float tb = 1099511627776; float gb = 1073741824; float mb = 1048576; float kb = 1024; char returnSize[256]; if( Bytes >= tb ) sprintf(returnSize, "%.2f TB", (float)Bytes/tb); else if( Bytes >= gb && Bytes < tb ) sprintf(returnSize, "%.2f GB", (float)Bytes/gb); else if( Bytes >= mb && Bytes < gb ) sprintf(returnSize, "%.2f MB", (float)Bytes/mb); else if( Bytes >= kb && Bytes < mb ) sprintf(returnSize, "%.2f KB", (float)Bytes/kb); else if ( Bytes < kb) sprintf(returnSize, "%.2f Bytes", Bytes); else sprintf(returnSize, "%.2f Bytes", Bytes); return returnSize; }
abuckau907 (04-05-2014)
You're returning the address of a local variable of the function.
Char* x = function(4000);
Char* y = function(8000);
Both point to the same char array. Not what you'd expect.
It works fine because the program you have written for verification is simple. In the real world, your function will break because what is returned exists on the stack and it will be overwritten eventually.
Fix'd.
Code:#include <cstdio> #include <windows.h> bool BytesToSize( double Bytes , char * ByteString , int BufSize ) { float tb = 1099511627776.0f; float gb = 1073741824.0f; float mb = 1048576.0f; float kb = 1024.0f; char * returnSize = (char *)malloc(BufSize); if(returnSize == NULL) return false; if( Bytes >= tb ) sprintf(returnSize, "%.2lf TB", (double)Bytes/tb); else if( Bytes >= gb && Bytes < tb ) sprintf(returnSize, "%.2lf GB", (double)Bytes/gb); else if( Bytes >= mb && Bytes < gb ) sprintf(returnSize, "%.2lf MB", (double)Bytes/mb); else if( Bytes >= kb && Bytes < mb ) sprintf(returnSize, "%.2lf KB", (double)Bytes/kb); else if ( Bytes < kb) sprintf(returnSize, "%.2lf Bytes", Bytes); else sprintf(returnSize, "%.2lf Bytes", Bytes); memcpy((void *)ByteString, (void *)returnSize, BufSize); free(returnSize); return true; } int main() { double baits = 9999999999999999999999.0f; char ByteString[512]; if(BytesToSize(baits, ByteString, sizeof(ByteString))) printf("%lf Bytes are %s \n", baits, ByteString); return 0; }
abuckau907 (04-05-2014)
Thanks @Harava
@OP
One more thing ..
If the first IF branch is not taken, that means bytes < tb --> No need to test for bytes < tb in the 2nd if clause.if( Bytes >= tb )
...
else if( Bytes >= gb && Bytes < tb )
...
else if( Bytes >= mb && Bytes < gb )
...
else if( Bytes >= kb && Bytes < mb )
...
else if ( Bytes < kb)
...
else
Same thing continues down -- all the conditions to the right of && were proven true in the previous if statement : P
if( Bytes >= tb )
...
else if( Bytes >= gb)
...
else if( Bytes >= mb)
...
else if( Bytes >= kb )
...
else
Last edited by abuckau907; 04-05-2014 at 12:14 PM.
'Some things that can be counted, don't matter. And some things that matter, can't be counted' - A.E.
--