Glibc detected free () invalid pointer

I have problems with dynamic memory allocation.

Below is just the test code I played with to try to fix the problem (this is the same problem in my current project code, this is just an easier way to show this).

#include<stdlib.h> #include<stdio.h> #include<assert.h> int main(){ int x = 5; int *ptr = (int*) malloc(sizeof(int)); assert(ptr != NULL); ptr = &x; printf("x = %d\n",x); *ptr = 3; printf("x = %d\n",x); free(ptr); return 0; } 

The program compiles in order and when I start, I get the correct outputs printed "x = 5 x = 3" But then I get the error message:

 glibc detected ./dnam: free(): invalid pointer: 0xbfccf698 

dnam is the name of the test program. From what I read about the error, it is supposedly caused by freeing up memory that you don't have malloc / calloc / realloc'd.

This error message is followed by backtracking and a memory card. At the end of the memory card, they told me that the program was interrupted (the kernel is reset).

+6
source share
3 answers
  int *ptr = (int*) malloc(sizeof(int)); ptr = &x; 

You change the ptr value! The compiler will take unlimited revenge if you try to free it.

Here:

 free(ptr); 

You are free - an object not allocated through malloc .

+11
source

You allocate memory and save its address in ptr. Then you point ptr to address x, so when you start free(ptr) you essentially free &x , which doesn't work.

tl; dr: there is no need for malloc and free when you assign a pointer to another var pointer.

+1
source

if you want to use this code. I think you should use the temp pointer to save init ptr.at last free (temp). like this:

  int *temp = ptr; free(temp); 
0
source

Source: https://habr.com/ru/post/957957/


All Articles