繁体   English   中英

返回指针的函数始终返回相同的值

[英]Function that returns a pointer always returns the same value

我对C ++编程相当陌生,无法理解当前项目出了什么问题。 我有大量的uint32_t,我想用预处理后的值填充。 第一次计算一切都很好,但是从第二次计算开始,仅*处理过的指针的内存地址发生变化,而不是其值发生变化。

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;
}

这将产生三个输出,其中两个相同。

此行似乎是将一次迭代的结果附加到更大的缓冲区中:

 memcpy(candPreprocessed + j * sizeof(uint32_t), processed, sizeof(uint32_t));

但是它仅复制4个字节(单个uint32_t )。 那可能是问题所在。

如果这问题,并且您将其解决,那么下一个问题将是目标缓冲区不足以容纳所有结果。

您提到了C ++编程-如果尝试实际使用C ++,您会发现这容易得多! std::vector会很有帮助。

由于问题的描述仍然很模糊(尽管有很多评论),所以我有点猜测:

memcpy(candPreprocessed + j * sizeof(uint32_t), processed, sizeof(uint32_t));

在我看来是错的。 candPreprocessed是指向uint32_t的指针。 我怀疑您实际上并不希望每4个条目将数据移动到candPreprocessed数组中。

尝试:

memcpy(candPreprocessed + j, processed, sizeof(uint32_t));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM