I am trying to reallocate a char ptr which possess some data. After reallocating to a size that is larger than current, part of the data is being overwritten.
The relevant part of the code is as follows:
char *convertToBinary(char *src, int *fractionPosition, bool double_precision) {
char *res = (char*)malloc(sizeof(char));
int currentResultPos = 0, precision;
int power = (strlen(src) - ((*fractionPosition) + 1)) * (-1);
float decimalValue_i = convertToInt(src, 10, 0, (*fractionPosition) - 1, 0);
float decimalValue_f = convertToInt(src, 10, (*fractionPosition) + 1,
strlen(src) - 1, power);
precision = determinePrecision(double_precision);
res = fromDecimalToDstinationBase(res, ¤tResultPos, 2,
decimalValue_i, &firstBinaryDigit);
res = convertFractionIntoResult(res, currentResultPos, 2,
decimalValue_f, precision);
*fractionPosition = currentResultPos - 1;
return res;
}
char *fromDecimalToDstinationBase(char *res, int *resPos, unsigned int dstB,
int decimalValue, char *firstDigit) {
int valueLength, sum = 0, power = 0;
while (decimalValue != 0) {
sum += (decimalValue % dstB) * pow(10, power++);
decimalValue /= dstB;
}
valueLength = countDecimalDigits(sum);
res = copyIntToStr(res, sum, resPos, valueLength);
return res;
}
char *copyIntToStr(char* res, int sum, int *resPos, int power) {
int remainder;
bool flag = true;
res = (char*)calloc(power + (*resPos) + 1, sizeof(char));
power--;
while (sum != 0) {
if (res[0] == '1' && flag) {
addFractionPoint(res, resPos);
flag = false;
}
remainder = sum % (int)pow(10, power);
res[(*resPos)++] = (sum / pow(10, power--)) + '0';;
sum = remainder;
}
res[*resPos] = '\0';
return res;
}
char *convertFractionIntoResult(char *res, int logicalS, unsigned int dstB,
float decimalValue, unsigned int precision) {
//here, logicalS = 5
int physicalS = logicalS, resRemainderCounter = 0;
float remainder = decimalValue;
// here, res = "1.101"
while (resRemainderCounter != precision) {
if (physicalS == logicalS) {
physicalS *= 2;
res = (char*)realloc(res, physicalS * sizeof(char));
// now, res = "1.1ÍÍÍÍÍÍÍýýýý"
}
I looked all over for an explanation. Does anyone knows why this could happen? what I might've done wrong?
EDIT:
also, I tried to replace physicalS with some random really large number, and it didn't change anything.