如何知道是否免费的C函数的工作吗? [英] How to know if C function free is working?

查看:152
本文介绍了如何知道是否免费的C函数的工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了下面的code的结果有些差异:

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);
}

让我解释一下:

在第三个呼叫根据我得到不同的结果,在Windows gargabge caracters,没有在Linux和Unix系统的Hello World印在OS的printf。

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。

问候。

推荐答案

使用指针已经释放不确定的行为后的结果。

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

这意味着该计划可能会打印垃圾,打印字符串的内容前,删除硬盘中,或者使猴子飞出的底部,并且仍然符合C标准。

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.

这篇关于如何知道是否免费的C函数的工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆