删除操作员的未定义行为

发布于 2025-01-25 16:36:41 字数 602 浏览 1 评论 0原文

我对C ++是相对较新的,我正在学习指针。我试图动态分配一些数组的内存,并发现了这个问题。

这是我的代码,

#include <iostream>

int main(){
    int n = 5;
    int *arr = new int(n*(sizeof(int)));

    for(int i=0; i<n; i++)
        *(arr+i) = i+1;

    delete[] arr;

    for(int i=0; i<n; i++)
        std::cout << *(arr+i) << " ";
}

预期的输出是一些垃圾值,因为我正在使用删除操作员释放内存,但是,这是我的输出:

第一次运行: 755597344 47626 2043 4 5

第二次运行: -1437908960 62859 2043 4 5

第三运行: -902037472 965 2043 4 5

我尝试过几次运行,但是只有前3个值更改,而其他数组似乎仍然存在,这可能是什么解释?

I am relatively new to C++ and I'm learning about pointers. I was trying to dynamically allocate some memory for an array and found this issue.

Here is my code,

#include <iostream>

int main(){
    int n = 5;
    int *arr = new int(n*(sizeof(int)));

    for(int i=0; i<n; i++)
        *(arr+i) = i+1;

    delete[] arr;

    for(int i=0; i<n; i++)
        std::cout << *(arr+i) << " ";
}

and the expected output is some garbage value since I'm freeing the memory with delete operator, however, this is my output instead:

First run:
755597344 47626 2043 4 5

Second run:
-1437908960 62859 2043 4 5

Third run:
-902037472 965 2043 4 5

I've tried several runs, but only first 3 values change, and the others seem as the array was still there, what could be the explanation for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七秒鱼° 2025-02-01 16:36:41

在一小部分代码中,有多个错误和问题:

  • expression new Int(n*(sizeof(int)))分配a single int值并将其初始化为值n*(sizeof(int))

    如果您想为int值分配空间,则需要new [],如new int [n]

  • 由于存在上述问题,您将从分配的内存的范围中,导致不确定的行为。。

  • 修复了第1号问题后,您需要将new []delete []操作员配对。不匹配的操作员也导致不确定的行为

  • 最后,一旦您删除了内存,就无法再访问它,并且任何尝试降低指针的尝试都会再次导致 不确定的行为


总而言之,程序应该看起来像这样:

#include <iostream>
#include <cstdlib>

int main()
{
    constexpr std::size_t n = 5;

    // Allocate memory
    int* arr = new[n];

    // Initialize the memory
    for (std::size_t i = 0; i < n; ++i)
    {
        arr[i] = i + 1;
    }

    // Display the memory
    for (std::size_t i = 0; i < n; ++i)
    {
        std::cout << "arr[" << i << "] = " << arr[i] << '\n';
    }

    // Free the memory
    delete[] arr;
}

在上述所有上述和完成的情况下,有更好的方法来创建固定或动态大小的数组。

如果您有一个固定尺寸的数组,其大小在编译时已知并且在运行时的大小将永远不会更改,请使用std :: Array而不是:

// Create and initialize array
std::array<int, 5> arr = {{ 1, 2, 3, 4, 5 }};

// Display array
for (int value : arr)
{
    std::cout << value << '\n';
}

如果在Compile中不知道大小 - 时间或大小在运行时需要更改,使用std :: vector而不是:

// Create a vector with five "zero-initialized" elements
std::vector<int> arr(5);

In the small piece of code there are multiple errors and problems:

  • The expression new int(n*(sizeof(int))) allocates a single int value and initializes it to the value n*(sizeof(int)).

    If you want to allocate space for an array of int values you need to use new[], as in new int[n]

  • Because of the above problem, you will go out of bounds of the allocated memory, leading to undefined behavior.

  • Once you fix issue number 1, you need to pair new[] with the delete[] operator. Mismatching operators also leads to undefined behavior.

  • And lastly, once you have deleted memory you can no longer access it, and any attempt of dereferencing the pointer will again lead to undefined behavior.

All in all the program should look something like this:

#include <iostream>
#include <cstdlib>

int main()
{
    constexpr std::size_t n = 5;

    // Allocate memory
    int* arr = new[n];

    // Initialize the memory
    for (std::size_t i = 0; i < n; ++i)
    {
        arr[i] = i + 1;
    }

    // Display the memory
    for (std::size_t i = 0; i < n; ++i)
    {
        std::cout << "arr[" << i << "] = " << arr[i] << '\n';
    }

    // Free the memory
    delete[] arr;
}

With all of the above said and done, there are better ways to create arrays of either fixed or dynamic size.

If you have a fixed-size array, whose size is known at compile-time and whose size will never change during run-time, use std::array instead:

// Create and initialize array
std::array<int, 5> arr = {{ 1, 2, 3, 4, 5 }};

// Display array
for (int value : arr)
{
    std::cout << value << '\n';
}

If the size is not known at compile-time, or the size will need to change during run-time, use std::vector instead:

// Create a vector with five "zero-initialized" elements
std::vector<int> arr(5);
北陌 2025-02-01 16:36:41
new int(n*(sizeof(int)));

这仅将单个int和设置值分配为n*(sizeof(int))

如果您想要一系列int,则必须像以下那样做。

   int *arr = new int[n];
new int(n*(sizeof(int)));

This allocates only single int and set value as n*(sizeof(int)).

If you want array of int, you have to do like below.

   int *arr = new int[n];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文