Code:

Function call:

char* converted = ConvertDoubleToStr(666654); printf("Converted string: %s \n", converted); 

Function:

 char* ConvertDoubleToStr(double d) { const int t = sizeof (double); char resultT[t] = " "; //int const dLength = sprintf(resultT, 0, "%lf", d); int const dLength = sprintf(resultT, "%lf", d); if (dLength < 0) return NULL; char *result = (char*)malloc(dLength + 1); if (result == NULL) return NULL; //int const resultLength = sprintf(result, dLength + 1, "%lf", d); int const resultLength = sprintf(result, "%lf", d); if (resultLength < 0) { free(result); return NULL; } printf("Converted string (d->s): %s \n", result); return result; } 

When exiting the function (by the way, the line printf("Converted string (d->s): %s \n", result); shows the correct result) when assigning the result of the function, I get an error:

enter image description here

Tell me, please, where am I wrong? thank

  • @ Enikeyschik does not fit, and return (char *) result too - Leonid Zolotarov 8:43 pm
  • What the hell is going on here? int const dLength = sprintf(resultT, "%lf", d); ? Write in 8 bytes a line much bigger ... - Harry

1 answer 1

666654.000000 is what you wrote in resultT , which is 8 in size (for what reasons? Because double is eight bytes?). Stack - shattered.


 int t = snprintf(NULL, 0, "%lf", d); char resultT[t + 1]; sprintf(resultT, "%lf", d); 
  • Yes, you are right, the problem is in the length of the array. And how, in my case, can I find out the required size of the result array before calling the "sprintf" function to fill it? - Leonid Zolotarov
  • @LeonidZolotarov You have already been told about the function snprintf . - Igor
  • I can't use 'snprintf' because it is for C ++, and I am writing in C. When adding a header file, I still could not use it - Leonid Zolotarov
  • @LeonidZolotarov Well write char resultT[100]; . - Igor
  • one
    @LeonidZolotarov snprintf is quite a function from C, more precisely from C99 - VTT 1:06 pm