+ 8

ensure free allocation memory

I asked 8 days ago how to ensure that the memory that I freed is absolutely freed look at this post https://www.sololearn.com/Discuss/1812954/?ref=app Bennett Post told me the correct way to do that but it is to complicated

31st May 2019, 11:04 PM
ABADA S
ABADA S - avatar
6 Antworten
+ 3
now I have this simple way to ensure that check that https://code.sololearn.com/c64zXgieYFg0/?ref=app when I free an almost freed memory I will see a runtime error so that the freed memory is really freed
31st May 2019, 11:08 PM
ABADA S
ABADA S - avatar
+ 3
I am sorry I didn't understand 😁
31st May 2019, 11:18 PM
ABADA S
ABADA S - avatar
+ 3
Cluck'n'Coder you changed p to NULL so you lost the memory that freed .. how to ensure free with that
1st Jun 2019, 8:15 AM
ABADA S
ABADA S - avatar
+ 2
There's no way to do that in C. Ensuring that freed memory is freed (which is guaranteed by the ANSI / ISO C standards) is about as futile as trying to determine if a string was null terminated or not. Using a debugger to track allocations and dangling pointers is probably your only option.
1st Jun 2019, 1:32 PM
Cluck'n'Coder
Cluck'n'Coder - avatar
+ 1
Allocated data is tracked by malloc() so your call to free() guarantees the memory pointed to by 'p' is freed. After the call to free(), 'p' is a dangling pointer so if you want to NULL check it, you'll have to make sure it points to NULL. Your second call to free() is undefined behavior and will most likely cause memory corruption.
31st May 2019, 11:14 PM
Cluck'n'Coder
Cluck'n'Coder - avatar
+ 1
The program you linked to will try to free 'p' twice. It doesn't check that 'p' wasn't already freed. You do not want to free memory that was not allocated. A good rule of thumb is that for every call to malloc() there should be a call to free() before the program exits. This is probably what you want: #include <stdio.h> #include <stdlib.h> int main(void) { int *p = malloc(4 * sizeof(int)); // free(p); <-- Uncomment these two // p = NULL; <-- and see what happens if (p != NULL) { printf("if the memory is not freed you will see me"); free(p); } return 0; }
1st Jun 2019, 12:26 AM
Cluck'n'Coder
Cluck'n'Coder - avatar