簡體   English   中英

這個指針和 memory 代碼打印是什么? 我不知道它是在打印垃圾還是如何打印我需要的值

[英]What is this pointer and memory code printing? I don't know if it's printing garbage or how to print the value that I need

這是我從一個更大的代碼片段中提取的代碼片段。 我需要弄清楚我打印的內容是否是垃圾以及如何更改它以打印我需要的值。 我需要它來打印int id的值,而不是打印的任何內容。 10813776在這次運行中是 10813776,當然,每當我更改一些代碼或重新啟動 DevC++ 時,它都會發生變化。

代碼是:

#include <iostream>
#include <memory> //Memory allocation (malloc)

using namespace std;

int main(){
    int id = 0;
    int nMemory = 0;
    int * pMemory;
    pMemory = (int *) malloc(20 * sizeof(int));
    
    while(id < 20){
        if (pMemory != NULL){
            cout << "Numbers in memory: " << endl;
            pMemory = new int[id];
            nMemory = *pMemory;
            cout << nMemory << endl;
        }
        id++;
    }
    delete pMemory;
    
    return 0;
}
pMemory = new int[id]; nMemory = *pMemory;

第一行用一個新的未初始化的數組替換了malloc的數組,然后嘗試從該新數組的第一個插槽中讀取。 您不應該直接分配給pMemory 可能是pMemory[someIndex] ,但不是pMemory本身。

您是否嘗試從pMemory數組中讀取並將其分配給nMemory 如果是這樣,請將上面的行更改為:

nMemory = pMemory[id];

你的整個循環應該看起來更像這樣:

if (pMemory != NULL) {
    cout << "Numbers in memory: " << endl;
    while(id < 20) {
        nMemory = pMemory[id];
        cout << nMemory << endl;
        id++;
    }
}

或者,使用更慣用for循環:

if (pMemory != NULL) {
    cout << "Numbers in memory: " << endl;
    for (int i = 0; i < 20; i++) {
        cout << pMemory[i] << endl;
    }
}

(您還必須在此循環上方的某個位置初始化數組。我假設您在真實代碼中這樣做,但如果不是:您發布的代碼使用malloc()分配了一個數組,但沒有將項目設置為有用值。確保在嘗試閱讀和打印它們之前將它們設置為有意義的值。)

此代碼正在泄漏您使用malloc()new[]分配的 memory 塊。

malloc()一塊 memory 並將其地址分配給pMemory ,然后將pMemory更改為指向使用new[]分配的不同 memory 地址。 所以你失去了free() malloc() 'ed memory 的能力(你甚至沒有嘗試調用free() )。

而且,此代碼未正確釋放分配有new[]的 memory。 new[]分配的 Memory 必須用delete[]釋放,而不是用delete 更糟糕的是,你在一個循環中調用了new[] 20 次,但在循環之后只調用了一次delete 因此,您正在泄漏 19 個new[] ed memory 塊,並且具有釋放 1 個塊的未定義行為

現在,為了回答您的實際問題,代碼打印出垃圾,因為您使用new[]分配的 memory未初始化,因此您嘗試從該 memory 打印的數據包含不確定的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM