07-27-2023, 10:55 AM
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).
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).