-2
#include <iostream>

using namespace std;

int *res=new int[0];

int res_size;

void multiply(int y);

void factorial(int x)

{

    res[0]=1;
    res_size=1;
    for (int i=2;i<=x;i++)
        multiply(i);
    for (int i=res_size-1;i>=0;i--)
        cout << res[i];
}

void multiply(int y)

{

    static int prod=1;
    int carry=0;
    for (int i=0;i<res_size;i++)
    {
        prod=res[i]*y+(carry);
        res[i]=prod%10;
        carry=prod/10;
    }
    while (carry)
    {
        res[res_size]=carry%10;
        carry=carry/10;
        res_size++;
    }
}

int main()

{

    int n;
    cout << "Enter a number" << endl;
    cin >> n;
    factorial(n);
    delete[] res;
    return 0;
}

When I am using delete[] operator why I am getting

Access violation reading location at address
4
  • 9
    you allocate space for 0 elements and then access the array out-of-bounds. Are you sure that the problem is the delete? Jun 1, 2020 at 22:17
  • 3
    use std::vector if you want to avoid this and many more problems. Jun 1, 2020 at 22:18
  • advice: you really shouldnt have res as global, you should pass it as arg to your functions
    – pm100
    Jun 1, 2020 at 22:59
  • Its working fine if I am not using delete operator so allocating space for 0 elements is not a problem as it is dynamically allocated. Jun 2, 2020 at 6:57

1 Answer 1

3

You allocated an array with zero elements

int *res=new int[0];

You may not write to such an array as you are doing

res[0]=1;

The program has undefined behavior.

Instead of the dynamically allocated array you could use the class template std::vector. In this case you could use the method push_back to add elements to the vector.

2
  • Note that simply replacing the array with a vector would not fix this code, because the vector would still have to be sized. Jun 1, 2020 at 22:53
  • @FredLarson He can use the method push_back to add elements to the vector. Jun 1, 2020 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.