jeudi 26 mars 2015

sprintf() precision .16 bug

I am relatively new to C and have to do a project for university so I chose to code a calculator/equation parser.


I have encountered a bug that occurs only when I set the precision in a sprintf()-call to 16. Everything works fine with any precision above or below and also 16 works fine in debug mode, too.


Expressions that cause my program to break:


12/(-9)+3 , but 12/(-9) works fine


(1)+(2)+(3) and similar things




So here's what the code does:


-it looks for the "upper" parantheses pair in the user entered string


-> j: position of the first char inside the parantheses


-> i: position of the first char after the parantheses


-calculate the inside of the parantheses recursively with the same function until there is no more pair of parantheses


-another function is called to cast this calculation into double


-return value of function is recursive call of concatenation of string[0 to j-2]##result_str[j to i-2]##string[i to end]




Here's the code that I think matters:



t= calloc (strlen(s), sizeof(char)); //string to store substring in
result_str= calloc (strlen(s), sizeof(char)); //string to store result of parantheses-calculation in
result_d= calc (subStr (result_str, s, j, i-j-1)); //call the function we're already in
sprintf (result_str, "%.16f", result_d); //cast result back to string, that's where the weird behaviour is caused (I think)
return calc (strcat (subStr (t, s, 0, j-1), strcat (result_str, s+i))); //recursive call of concatenated string described as above


-subStr() is just a function that uses strncpy() with error handling calc() is the function we're in


-s is the *char given by the user




I hope I didn't forget anything. If more code or info is needed just comment. I can also supply the *.exe to try out.


And remember: Everything works fine with sprintf (result_str, "%.17f", result_d); So I guess it can't be array out of bound (I think)


Thanks to all of you in advance!


P.S.: if anyone has an idea of how to avoid the re-casting of a double to string, please say so.


Aucun commentaire:

Enregistrer un commentaire