我对 C++ 编程相当陌生,我很难理解我当前项目的问题所在。我有一大堆 uint32_t 我想用预处理值填充。对于第一次计算来说一切都很好,但是从第二次开始,只有 *processed 指针的内存地址发生了变化,而不是它的值。
uint32_t *candPreprocessed = (uint32_t*) malloc(sizeof(uint32_t) * indices.size());
for(int j = 0; j < indices.size()-1; j++)
{
char *candidate = (char*) malloc(sizeof(char) * (indices[j+1] - indices[j]) + 1);
...
uint32_t *processed = preprocess((uint8_t*) candidate, len);
memcpy(candPreprocessed + j * sizeof(uint32_t), processed, sizeof(uint32_t));
processed = NULL;
// free the messages
free(candidate);
free(processed);
}
预处理如下所示:
uint32_t* preprocess(uint8_t *word, size_t wordLength)
{
uint8_t *toProcess = (uint8_t*) calloc(120, 1);
...
return (uint32_t*) (toProcess);
}
据我了解,free(processed) 调用应该释放在预处理期间创建的指针所占用的内存。在循环的以下迭代中,获取一个新的候选并计算一个新的长度,因此参数发生了变化。我错过了什么,为什么这没有反映在输出中?
谁能指出我正确的方向?提前致谢!
编辑:根据要求,简短的自包含编译示例 -
#include <iostream>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
uint32_t* preprocess(uint8_t *word, size_t wordLength)
{
// preprocessing
uint8_t *toProcess = (uint8_t*) calloc(120, 1);
memcpy(toProcess, word, wordLength);
toProcess[wordLength] = 128;
int numBits = 8 * wordLength;
memcpy(toProcess + 56, &numBits, 1);
return (uint32_t*) (toProcess);
}
int main(int argc, char* argv[])
{
char cand[12] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'};
int indices[4] = {0,4,8,12};
for(int j = 0; j < 3; j++)
{
// extract the message from the wordlist
char *candidate = (char*) malloc(sizeof(char) * (4) + 1);
int i=0;
for(int k = indices[j]; k < indices[j+1]; k++)
candidate[i++] = cand[k];
candidate[i] = '\0';
size_t len = strlen(candidate);
uint32_t *processed = preprocess((uint8_t*) candidate, len);
std::cout << processed << std::endl;
// free the messages
free(candidate);
free(processed);
}
return 0;
}
这会产生三个输出,其中两个是相同的。