How to find out if the C function works for free?

I saw some differences as a 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 OSfree printf call, I get different results, gargabge characters on Windows, nothing on Linux and on the Unix system "Hello World" is printed.

Is there a way to check the status of a pointer to find out when the memory was freed?

I think this printing mechanism cannot be trusted all the time.

Thnaks.

Hey.

+3
source share
3 answers

Using a pointer after it is freed results in undefined behavior.

This means that the program can print garbage, print the previous contents of the string, erase your hard drive or pull monkeys from its bottom and still comply with the C standard.

", ". , , .

+8

free(), . , , , free().

nil , . , , non-nil .

+5

ansewr: , C. , , , - undefined, ( SEGFAULT ).

, , , , Valgrind.

+3

All Articles