Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glibc detected free() invalid pointer

Tags:

c

I'm having a bit of trouble with some dynamic memory allocation.

Below is just a test code that I've been playing around with to try and fix the problem (it's the same problem in my current project's code, this is just a simpler way to show it).

#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 fine and when run I get the correct outputs printed "x = 5 x = 3" But then I get the error:

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

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

This error message is followed by a backtrace and a memory map. AT the end of the memory map I'm told the program has aborted (core dumped).

like image 541
Lukas Avatar asked Nov 12 '13 22:11

Lukas


2 Answers

   int *ptr = (int*) malloc(sizeof(int));

   ptr = &x;

You are changing ptr value! The compiler will be taking unlimited revenge if you attempt to free it.

Here:

free(ptr);

You are free-ing an object not allocated through malloc.

like image 124
ouah Avatar answered Nov 04 '22 07:11

ouah


You are allocating memory and saving its address into ptr. Then, you make ptr point to x's address, thus when you run free(ptr) you essentially freeing &x, which doesn't work.

tl;dr: there's no need for malloc and free when you're assigning the pointer a pointer to another var.

like image 1
Ron Avatar answered Nov 04 '22 06:11

Ron