开发者

How to know if C function free is working?

开发者 https://www.devze.com 2023-02-18 10:52 出处:网络
I have seen some differences开发者_开发百科 in the result of the following code: #include <stdio.h>

I have seen some differences开发者_开发百科 in the result of the following code:

#include <stdio.h>
#include <malloc.h>
#include <string.h>

int main(void)
{
 char* ptr;
 ptr = (char*)malloc(sizeof(char) * 12);
 strcpy(ptr, "Hello World");

 printf("%s\n", ptr);
 printf("FREEING ?\n");

 free(ptr);

 printf("%s\n", ptr);
}

Let me explain:

In the third call to printf depending the OS I get different results, gargabge caracters in Windows, nothing in Linux and in A Unix system "Hello World" is printed.

Is there a way to check the status of the pointer to know when memory has been freed?

I think this mechanism of print can not be trusted all the times.

Thnaks.

Greetings.


Using a pointer after it has been freed results in undefined behavior.

That means the program may print garbage, print the former contents of the string, erase your hard drive, or make monkeys fly out of your bottom, and still be in compliance with the C standard.

There's no way to look at a pointer and "know when memory has been freed". It's up to you as a programmer to keep track.


If you call free(), the memory will have been freed when that function returns. That doesn't mean that the memory will be overwritten immediately, but it's nevertheless unsafe to use any pointer on which you've called free().

It's a good idea to always assign nil to a pointer variable once you've freed it. That way, you know that non-nil pointers are safe to use.


Simple ansewr: you can't check if a pointer has been freed already in C. Different behaviors are probably due to different compilers, as using a pointer after freeing it is undefined you can get all sorts of behavior (including a SEGFAULT and program termination).

If you want to check if you use free property and your program is memory leak free, then use a tool like Valgrind.

0

精彩评论

暂无评论...
验证码 换一张
取 消