簡體   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