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).
   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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With