Lukas
Lukas

Reputation: 73

glibc detected free() invalid pointer

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).

Upvotes: 7

Views: 20863

Answers (3)

MYLOGOS
MYLOGOS

Reputation: 681

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

 int *temp = ptr;


  free(temp);

Upvotes: 0

Ron
Ron

Reputation: 2019

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.

Upvotes: 1

ouah
ouah

Reputation: 145919

   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.

Upvotes: 12

Related Questions