【问题标题】:Segmentation fault when deleting a Array [closed]删除数组时出现分段错误[关闭]
【发布时间】:2017-08-15 15:12:00
【问题描述】:

我已经简化了以下函数,在使用后尝试删除数组时出现段错误。

float * MyService::innerFunction(MyClass& feature) {
    float* target = new float[1];
    target[0] = feature.getValue();
    target[1] = 1;
    return target;
}

float MyService::outerFunction(MyClass& feature){
    float* input = innerFunction(feature);
    ...
    delete[] input; <- seg fault
    return result;
}

【问题讨论】:

  • 恭喜,您已经删除了代码中存在错误的部分。
  • 对不起,我(简化)添加了导致错误的行......但不知何故,段错误发生在删除时,而不是在设置 var 时
  • 未定义的行为是未定义的。
  • 你的问题到底是什么?
  • 这不是 Java 或 c#。当你做未定义的事情时,你会得到未定义的行为。你不能指望它在你弄错这些东西的时候就崩溃。

标签: c++ arrays segmentation-fault


【解决方案1】:

您的数组太小。 float* target = new float[1]; 仅分配一个元素,但您分配了两个。 target[1] = 1; 毁了你的脑袋。

所以你需要这样做:

float* target = new float[2];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多