gpt4 book ai didi

c - realloc 正在覆盖数据

转载 作者:行者123 更新时间:2023-11-30 15:03:38 27 4
gpt4 key购买 nike

我正在尝试重新分配拥有一些数据的 char ptr。重新分配到大于当前大小后,部分数据将被覆盖。

相关部分代码如下:

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, &currentResultPos, 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ÍÍÍÍÍÍÍýýýý"
}

我到处寻找解释。有谁知道为什么会发生这种情况?我可能做错了什么?

编辑:

另外,我尝试用一​​些随机的非常大的数字替换physicalS,但它没有改变任何东西。

最佳答案

看来您正在使用 Microsoft 的编译器和库。在 Debug模式下,该库会使用各种值填充内存中未初始化的部分,这些值旨在在调试时脱颖而出,以帮助您检测错误。

您看到的Í对应于0xCD,这是库用来标记堆内存未初始化部分的值。 ý 对应于 0xFD,库用它来标记超出堆分配末端的区域。维基百科可以告诉你很多关于这些的信息 magic numbers .

让我们看看您的代码:

// here, res = "1.101"
// ...
physicalS *= 2;
res = (char*)realloc(res, physicalS * sizeof(char));
// now, res = "1.1ÍÍÍÍÍÍÍýýýý"

如果可以的话,realloc 应该返回一个至少具有请求大小的缓冲区。它可能是原始缓冲区、扩展缓冲区,也可能是新缓冲区。如果它是一个新缓冲区,并且新缓冲区比原始缓冲区大,则应将原始缓冲区的内容复制到新缓冲区。库的调试版本将用 0xCD 填充新缓冲区的其余部分。

所以这个结果告诉我,当你认为 res 指向 "1.101" 时,它实际上指向一个包含 1.1 的未终止缓冲区后面恰好是01,这可能是缓冲区溢出的结果。

然后,您请求更大的缓冲区,1.1 被忠实地复制到开头,然后调试库用 0xCD 字节填充新缓冲区的剩余部分,以表明它是未初始化的堆内存。

在这种情况下,我将使用调试器来观察每个 malloc 和 realloc 的实际缓冲区大小,并检查代码是否实际上覆盖了缓冲区的末尾。

关于c - realloc 正在覆盖数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40687347/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com