【问题标题】:C++ crashes upon running but only some of the timeC++ 在运行时崩溃,但只是在某些时候
【发布时间】:2016-01-13 08:12:12
【问题描述】:

这是我的代码。当我运行某些时间时,它会像我预期的那样打印“1.5969”。大约三分之一的时间它说 .exe 文件已停止工作并且“Windows 正在寻找解决方案”类型错误。如果我不调用 test() 它会 100% 的工作。如果我在 test() 之后省略了所有代码,但保持对 test() 的调用,它 100% 的时间都可以工作。当代码按原样编写时,它的工作时间大约有三分之一。这是为什么呢?

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

int test(int* b, int* c){
   ++*c;
   b[6] = 3;
   return b[6];
}

int main(){
    int* a;
    int c = 1;
    int* d = &c;
    a = new int[5];
    test(a, d);

    char a_[] = "1.5969 1.68 1.88";
    char* pEnd;
    double d1;
    d1 = strtod(a_,&pEnd);
    cout  << d1;
    return 0;
}

【问题讨论】:

  • abcdd1a_ 并不是你能想象到的最好的变量名......
  • a = new int[5]; 创建一个包含 5 个元素的对象。访问索引 6 当然是行不通的。
  • 你是在一个曲折的小通道的迷宫中,都一样。使用有意义的变量名。

标签: c++ pointers reference crash


【解决方案1】:

test() 中的数组索引超出范围。分配的最大空间为 5 个int,但访问第 7 个数字。这会导致未定义的行为。确保test()b 的索引在0 到4 之间。

【讨论】:

    【解决方案2】:

    您访问超出范围。 a = new int[5]; 分配 5 个数组元素。但是b[6] 访问数组的第 7 个元素。像这样调整你的代码:

    int test(int* b, int* c){
       ++*c;
       b[6] = 3;
       return b[6];
    }
    
    int main(){
        int* a;
        int c = 1;
        int* d = &c;
        a = new int[7];
                 // ^
        test(a, d);
    
        char a_[] = "1.5969 1.68 1.88";
        char *pEnd;
        double d1;
        d1 = strtod(a_,&pEnd);
        cout  << d1;
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      相关资源
      最近更新 更多