TransWikia.com

Why don't need to use free() function in this case?

Stack Overflow Asked by akrilmokus on February 4, 2021

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("%dn", *ptr);
  }
  free(ptr);
  return 0;
}

2 Answers

The pointer value you pass to free must be a value returned by malloc, calloc, or realloc. In this case you reassigned ptr with the address of i, which was not the result of a *alloc call. Note that in the process you lost your only reference to the dynamically-allocated memory, so you don’t have a way to free it later; this is known as a memory leak.

You get the same problem if you do something like ptr++ - you’re still pointing within the dynamically-allocated block, but again it’s not the address returned by *alloc so you get the same error.

Answered by John Bode on February 4, 2021

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.

Answered by Krishna Kanth Yenumula on February 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP