Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 268 Vote(s) - 3.43 Average
  • 1
  • 2
  • 3
  • 4
  • 5
glibc detected free() invalid pointer

#1
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).
Reply

#2
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`.
Reply

#3
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.
Reply

#4
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);

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through