Search code examples
c++memory-managementmallocnew-operator

Why does new and malloc output different results?


This is my code;

#include <cstdio>
#include <cstdlib>
using namespace std;

int MIN(int a, int b)
{
    if (a <= b) return a;
    else return b;
}

int main(void)
{
    int a; 
    scanf("%d", &a);

    int *n = new int[a];
    //int *n = (int *)malloc(sizeof(int)*(a));
    for (int i = 0; i < a; i++)
        n[i] = a;

    n[a] = 0;

    for (int i = a; i > 1; i--)
    {
        if (i % 3 == 0) n[i / 3] = MIN(n[i] + 1, n[i / 3]);
        else if (i % 2 == 0) n[i / 2] = MIN(n[i] + 1, n[i / 2]);
        n[i - 1] = MIN(n[i] + 1, n[i - 1]);
    }

    printf("%d", n[1]);

    delete[] n;
    //free(n);
    return 0;
}

If you use new, nothing happens.

However, using malloc will cause a heap corruption detected error.

I wonder why this is happening and what's different from new and malloc.


Solution

  • n[a] = 0;
    

    this line and further accessing the element in the array n with the index a causes undefined behavior, that is why the program crashes sometimes.

    If you need to process the element with the index a, then allocate enough memory for that:

    int *n = new int[a + 1];