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
.
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];
n[a] = 0;
is an Undefined behavior. Even if you use malloc
it is undefined behavior. And it is logical to stop reasoning the undefined behavior given that they are undefined and not depenedent on the function used or anything you might think of.
Accessing array index out of bound is undefined behavior.
Also if you are using scanf
use it properly - the result that scanf
returns should be checked to know whether it is successful or not.
Note that , your idea of that using new
and malloc
is creating differemt behavior is wrong. This is one of the things with udnefined behavior. It might work also - but that doesn't mean that it would work definitively every single time. Be careful.
Also you can use malloc
to allocate necessary amounts of memory. (Ofcourse you can do that with new
too).
if( (n=malloc(sizeof(*n)*(a+1)))==NULL){
perror("malloc");
exit(EXIT_FAILURE);
}
Allocated memory using malloc
should only be freed using free
and for new
it would be delete
. Otherwise it is erroneous.
new
and malloc
output different results because one is C++ and the other is C. There is a whole different implementation of the two. See also the other answers that tell you your program has UB.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.