它是安全释放它们指向什么后重用指针变量? [英] Is it safe to reuse pointers variables after freeing what they point to?

查看:122
本文介绍了它是安全释放它们指向什么后重用指针变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是安全和predictable来释放它们指向的数据后,再使用指针?

Is it safe and predictable to reuse pointers after freeing the data they point to?

例如:

char* fileNames[] = { "words.txt", "moreWords.txt" };
char** words = NULL;
int* wordsCount = NULL;
for ( i = 0; i < 2; ++i ) {
    data = fopen( fileNames[i], "r" );
    words = readWords( data );
    wordsCount = countWords( words );

    free( wordsCount );
    for ( j = 0; words[j]; ++j )
        free( words[j] );
    free( words );
    fclose( data );
}

省略

*错误检查

*error checking omitted

我运行了code,它似乎运行(没有警告,错误或内存问题),但我想知道如果这是安全和predictable在大多数环境中使用(特别是在典型的Linux环境)?

I am running the code and it appears to run (no warnings, errors, or memory problems) but I am wondering if this is safe and predictable to use in most environments (specifically in a typical Linux environment)?

如果这不是安全和predictable',什么是完成在两个不同的文件相同的操作的最佳方式,短创造两次指针的金额等的

If this isn't 'safe and predictable', what is the best way to accomplish the same operations on two different files, short of creating two times the amount of pointers, etc?

编辑:我要问,如果它是没关系释放它所指向后重用指针的变量。我知道你不应该释放后使用指针的即可。
假设code完美的作品(它的工作原理如预期,内存被释放正确等等)。我不能改变的规范。对于这项任务。

I am asking if it is okay to reusing a pointer variable after freeing what it pointed to. I understand you should not use a pointer value after freeing. Assume the code works perfectly (it works as intended, memory is being freed correctly and such). I cannot change the spec. for this assignment.

谢谢!

推荐答案

你在做什么是好的。因为你发布一个指针后,你重新初始化你重用之前

What you're doing is fine: because, after you release a pointer, you're reinitializing it before you reuse it.

如果问题是它是安全的释放后重用指针,那么答案是否。

If the question is "is it safe to reuse a pointer value after freeing it" then the answer is "no".

如果问题是它是安全的释放它的价值后,再利用一个指针变量,那么答案是是的,只要你把它重新初始化到一个(新)有效值你重用前

If the question is "is it safe to reuse a pointer variable after freeing its value" then the answer is "yes, provided you reinitialize it to a (new) valid value before you reuse it".

这篇关于它是安全释放它们指向什么后重用指针变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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