So it'is a simple code. I won't explain it further. My problem is, if I use free()
it cause an
*** Error in `./main': free(): invalid pointer: 0x00007ffee58389f8 *** error,
but I am not exactly understand why. It is because I gave a loop variable address to the ptr? If I remove free()
function call, it works perfectly, but I am curious what cause this.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
printf("Give me a number:\n");
scanf("%d", &num);
int *ptr = malloc(sizeof(int) * num);
for (int i = 0; i < num; ++i)
{
ptr = &i;
printf("%d\n", *ptr);
}
free(ptr);
return 0;
}
From Valgrind:
Definitely lost". This means that no pointer to the block can be found. The block is classified as "lost", because the programmer could not possibly have freed it at program exit, since no pointer to it exists. This is likely a symptom of having lost the pointer at some earlier point in the program. Such cases should be fixed by the programmer.
In the code, pointer to the malloc'ed memory has been modified (ptr = &i
) So, we lost the pointer to the memory.
And, you shouldn't free stack memory.