c++ - new什么时候分配内存?

标签 c++ memory-management dictionary new-operator

<分区>

我有以下程序:

#include<iostream>
#include<map>

using namespace std;

int  *ar;

int main(int argc, const char *argv[])
{
    int N,i;
    map <int , int> W;
    ar = new int[N+1];
    cin >> N;
    for (i = 1; i <= N; i++) {
        cin >> ar[i];
    }
    W[ar[N]]= -1;   
    return 0;
}

我给程序提供以下输入:

6

1 1 2 2 3 4

如果我使用 g++ -O 选项(没有优化)编译上面的代码,我会在该行得到 segabrt

W[ar[N]]= -1;

两个问题:

  1. 是不是ar[]没有被new分配内存?如果我用某个常数值替换该行,我会得到同样的错误。

    W[4] = -1;
    
  2. map 是否需要某种初始化?它通常无需初始化即可工作。

最佳答案

你有这两行倒过来:

ar = new int[N+1];   // Here the value of 'N' is undefined (random)
                     // So the number of values you get is also random (+1)
cin >> N;

使用前需要加载N:

cin >> N;
ar = new int[N+1];  // Now N is defined and you get the requested number of values.

关于c++ - new什么时候分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14080084/

相关文章:

c++ - libx264:哪些参数可以动态更改?

c++ - 如何从OpenCV中的目录中依次读取文件并用于处理?

macos - 10.7 上的 ARC 迁移工具给出错误 : it is not safe to remove an unused 'autorelease' message

c - 在给定内存硬限制的情况下确定内存管理的位 vector 的大小

Python:按照插入项目的顺序迭代字典

python - 比较并返回字典字符串值?

c# - 使用基于值的串联重复键构建一个新字典

c++ - Qt QMenu 设置样式表

c++ - 重载运算符的模板 : error: overloaded 'operator*' must have at least one parameter of class or enumeration type

pointers - 我可以返回一个结构,该结构使用特征实现中的 PhantomData 来为原始指针添加生命周期而不污染接口(interface)吗?