Andyo
Andyo

Reputation: 19

C++ crashes upon running but only some of the time

This is my code. When I run some of the times it prints "1.5969" like I expect. About a third of the time it says the .exe file has stopped working and "windows is looking for a solution" type error. If I do not call test() it works 100% of the time. If I omit all of the code after test() but keep the call to test() it works 100% of the time. When the code is as written it works about a third of the time. Why is this?

#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;
}

Upvotes: 1

Views: 57

Answers (2)

Rabbid76
Rabbid76

Reputation: 211248

You access ot ouf bounds. a = new int[5]; allocates 5 array elements. But b[6] access the 7th element of the array. Adapt your code like this:

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;
}

Upvotes: 1

Erobrere
Erobrere

Reputation: 388

Array index out of bounds in test(). Maximum space allocated is for 5 int but accessing the 7th number. This results in undefined behavior. Make sure index of b in test() is between 0 and 4.

Upvotes: 1

Related Questions