跟踪动态内存

3
#include <iostream>
#include <cctype> // for isdigit function
int main()
{
    int initial_size = 10;
    int* temp = new int[initial_size];
    int actual_size = 0;
    while ( 1 )
    {
        char ch;
        cin >> ch;
        if ( ch == 'E' )
            break;
        if ( isdigit(ch) ){
            cin.unget();    
            int n;
            cin >> n;       //If it's an integer, store it.
            actual_size++;  // Keep tracks of actual size.
            if ( actual_size <= initial_size )
                *temp++ = n; //Storing in temp array...

            else if ( actual_size > initial_size ){ //When there's not enough space in array..
                int old_initial_size = initial_size; 
                initial_size *= 2; //Doubling the size of initial_size after storing it in old_initial_size.
                int* hold = new int[old_initial_size]; 
                for ( int i = 0; i < old_initial_size; i++)
                    hold[i] = temp[i];   // From temp to hold.This is my attempt at keeping the values of temp array.

                temp = new int[initial_size]; // After passing every value in temp i resize it.

                for ( int i = 0; i < old_initial_size; i++)
                    temp[i] = hold[i];     //From hold to newly created temp.

                delete[] hold;  

            }
        }
    }
    int* actualArray = new int[actual_size];
    for ( int i = 0; i < actual_size; i++)
        actualArray[i] = temp[i];

    delete[] temp;  

    for ( int i = 0; i < actual_size; i++)
        cout << actualArray[i] << " ";

}

这是我想要做的事情:
我想一直从用户那里获取输入,直到输入 E 为止。如果输入是整数,我想将其存储在预定义的临时动态数组中,该数组大小为10。
在此过程中,我想计算实际数字输入的数量。如果超过临时数组的初始大小,则希望将临时数组的大小加倍,同时保留其中的旧输入。
当循环终止时,我想将临时数组中的输入传递给我的实际数组,其大小与数字输入完全相同(实际大小)。
您可以看到我的尝试以上面的代码为例。输出结果是随机数字,但至少我得到了正确数量的随机数字。
例如,如果我输入“3 4 E”,我会得到类似于“13123213 1541321231”的东西。

2
让自己轻松一点,使用 std::vector。我相信你的代码中至少有一个内存泄漏。 - chris
那样太容易了 :) 我的动力只是为了学习。 - SpiderRico
1个回答

3

这个问题的根源在于语句*temp++ = n;。实际上你是在增加指针,所以在使用循环遍历temp之后它已经不再指向内存的开头。这就是为什么你看到随机数字的原因。

我建议改为:

   temp[actual_size - 1] = n; //Storing in temp array...

我应该补充一下,您的重新分配代码比必要的复杂得多。您只需要一个新数组,memcpy旧值,将temp设置为新数组并释放旧数组。
int *oldArray = temp;
temp = new int[initial_size];
memcpy(temp, oldArray, old_initial_size * sizeof(int));
delete [] oldArray;
temp[old_initial_size] = n;

搞定了,老铁! - SpiderRico
几乎……我在actual_array[10]处得到了一个随机数,其他元素都没问题。 - SpiderRico
@user2362377,这是因为当您重新分配内存时,您忘记将新的int保存在'temp'中。 - Guillaume

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接