确保数据正确存储在 c++大批

发布于 2025-01-17 07:25:50 字数 300 浏览 3 评论 0原文

我有一个很大的代码,我正在尝试将其集成到现有程序中。为此,我需要使用 c++ 二维和一维数组。我最熟悉的是Python;如果我尝试

import numpy as np
x = np.zeros(10)
x[20] = 3
print(x[15])

第 3 行和第 4 行都会导致错误发生。在 C++ 中,这不会导致错误,相反,代码中的某个位置可能会出现段错误(或者计算出的答案毫无意义)。我的问题是,如何确保 C++ 数组中的内存分配/访问正确?编译器选项或调试工具是否有助于解决此问题?我正在使用 g++ 来编译代码。

I have a large code I'm trying to integrate into an existing program. For this, I need to work with c++ 2d and 1d arrays. I'm most familiar with python; if I tried

import numpy as np
x = np.zeros(10)
x[20] = 3
print(x[15])

Both lines 3 and 4 would cause an error to occur. In c++, this doesn't cause an error, instead a segfault will likely occur somewhere in the code (or the computed answer is meaningless). My question is, how can I ensure memory assignment/access in a c++ array is correct? Are the compiler options or debugging tools that would help with this? I am using g++ to compile the code.

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

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

发布评论

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

评论(2

別甾虛僞 2025-01-24 07:25:50

使用原始数组,除了您自己跟踪实际尺寸的情况下,没有办法。

在C ++中,您只为使用的费用付费。换句话说,范围检查取决于开发人员的实施,因此它不会惩罚实际不需要的人。

一个好的做法是不使用原始数组,而是使用标准容器(std :: Arraystd :: vector,...)。他们拥有自己的数据并跟踪您的大小。

使用标准容器,有一个at()成员函数,它可以抛出 std :: out_of_range异常如果您尝试访问界限索引。
另一方面,如果您不想处理异常,则仍然可以使用size()成员函数手动进行界限。


您的示例湾的一个有效实现是:

std::vector<int> x(10, 0); // Vector of 10 elements initialized with value 0
  • 界限检查与异常处理:
try
{
    x.at(12) = 3; // at()
}
catch(std::exception & e)
{
    std::cout << e.what() << std::endl;
}
  • 手动界限检查:
if(12 < x.size())
    x[12] = 3; // operator[]

注意: std :: vector需要#include&lt; vector&gt; and std :: array需要#include&lt; array&gt;

With raw arrays, there is no way except if you keep track of the actual size yourself.

In C++, you only pay for what you use. In other words, the bounds checking is up to the developer to implement so that it won't penalize someone who does not actually need it.

A good practice is to not use raw arrays but use standard containers instead (std::array, std::vector, ...). They own their data and keep track of the size for you.

With standard containers, there is an at() member function that throws an std::out_of_range exception if you try to access an out of bounds index.
On the other hand, if you don't want to handle the exception, you still can do the bounds checking manually using the size() member function.


One valid implementation of your example bay be:

std::vector<int> x(10, 0); // Vector of 10 elements initialized with value 0
  • Bounds checking with exception handling:
try
{
    x.at(12) = 3; // at()
}
catch(std::exception & e)
{
    std::cout << e.what() << std::endl;
}
  • Manual bounds checking:
if(12 < x.size())
    x[12] = 3; // operator[]

Note: std::vector requires to #include <vector> and std::array requires to #include <array>.

故事↓在人 2025-01-24 07:25:50

如果您使用问题中所示的文字索引,编译器会警告您:

#include <stdio.h>

int main() {
        int thing[2] = {0};
        printf("%d", thing[3]);
        return 0;
}
test.cpp:5:15: warning: array index 3 is past the end of the array (which contains 2 elements) [-Warray-bounds]
        printf("%d", thing[3]);
                     ^     ~
test.cpp:4:2: note: array 'thing' declared here
        int thing[2] = {0};
        ^
1 warning generated.

但是,如果您使用变量对数组进行索引,并且该变量的值超出范围,则编译器不会生成错误。例如:

#include <stdio.h>

int main() {
    int thing[2] = {0};
    int index = 3;
    printf("%d", thing[index]);
    return 0;
}

这里的行为是未定义的,编译器不会让你知道。在这些情况下,您能做的最好的事情就是在数组访问之前进行检查。

The compiler will warn you if you use a literal index like shown in your question:

#include <stdio.h>

int main() {
        int thing[2] = {0};
        printf("%d", thing[3]);
        return 0;
}
test.cpp:5:15: warning: array index 3 is past the end of the array (which contains 2 elements) [-Warray-bounds]
        printf("%d", thing[3]);
                     ^     ~
test.cpp:4:2: note: array 'thing' declared here
        int thing[2] = {0};
        ^
1 warning generated.

It will not, however, generate an error if you use a variable to index into the array, and the value of that variable is out-of-range. For example:

#include <stdio.h>

int main() {
    int thing[2] = {0};
    int index = 3;
    printf("%d", thing[index]);
    return 0;
}

The behaviour here is undefined, and the compiler won't let you know. The best you can do in these cases is put a check in place before the array access.

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