相关疑难解决方法(0)

免费后将变量设置为NULL

在我的公司中,有一个编码规则,在释放任何内存后,将变量重置为NULL.例如 ...

void some_func () 
{
    int *nPtr;

    nPtr = malloc (100);

    free (nPtr);
    nPtr = NULL;

    return;
}
Run Code Online (Sandbox Code Playgroud)

我觉得,在上面显示的代码中,设置为NULL没有任何意义.或者我错过了什么?

如果在这种情况下没有任何意义,我将采用"质量团队"来删除此编码规则.请指教.

c malloc free coding-style heap-memory

146
推荐指数
11
解决办法
8万
查看次数

free()将内存归零吗?

直到今天,我仍然相信,调用free()内存空间会释放它以供进一步分配而无需任何其他修改.特别是,考虑到这个SO问题清楚地表明free()不会将内存归零.

但是,让我们考虑这段代码(test.c):

#include<stdlib.h>
#include<stdio.h>

int main()
{
    int* pointer;

    if (NULL == (pointer = malloc(sizeof(*pointer))))
        return EXIT_FAILURE;

    *pointer = 1337;

    printf("Before free(): %p, %d\n", pointer, *pointer);

    free(pointer);

    printf("After free(): %p, %d\n", pointer, *pointer);

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

编译(GCC和Clang):

gcc test.c -o test_gcc
clang test.c -o test_clang
Run Code Online (Sandbox Code Playgroud)

结果:

$ ./test_gcc 
Before free(): 0x719010, 1337
After free(): 0x719010, 0
$ ./test_clang
Before free: 0x19d2010, 1337
After free: 0x19d2010, 0
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我一直生活在谎言中还是我误解了一些基本概念?还是有更好的解释?

一些技术信息:

Linux 4.0.1-1-ARCH x86_64
gcc version 4.9.2 …
Run Code Online (Sandbox Code Playgroud)

c free gcc memory-management clang

35
推荐指数
6
解决办法
4740
查看次数

为什么不为C++提供DELETE宏的原因

有没有什么好的理由(除了"宏是邪恶的",也许)不使用以下宏?

#define DELETE( ptr ) \
if (ptr != NULL)      \
{                     \
    delete ptr;       \
    ptr = NULL;       \
}

#define DELETE_TABLE( ptr ) \
if (ptr != NULL)            \
{                           \
    delete[] ptr;           \
    ptr = NULL;             \
}
Run Code Online (Sandbox Code Playgroud)

c++ macros pointers memory-management

17
推荐指数
6
解决办法
8826
查看次数

使用SecureZeroMemory()真的有助于使应用程序更安全吗?

WinAPI中有一个SecureZeroMemory()函数,用于在不再需要缓冲区时擦除用于存储密码/加密密钥/类似内容的内存.它与ZeroMemory()的不同之处在于它的调用不会被编译器优化掉.

是否真的有必要擦除用于存储敏感数据的内存?它真的能使应用程序更安全吗?

我知道数据可以写入交换文件或休眠文件,其他进程可能会读取我程序的内存.但是当数据仍在使用时,同样可能发生.为什么使用,然后擦除使用更好?

c++ security winapi

7
推荐指数
2
解决办法
2347
查看次数

是否可以通过分配内存来恢复秘密数据(例如用于解密的空闲内存中的RSA私钥)?

例如,让我们采用伪代码,该伪代码尝试free使用此方法将RSA私钥存储在已分配(然后是d)的内存中:

int main(){
    bigNum priKey;


    while(true) {
        void *mem = malloc(2024); //allocate a good amount of chunk

        if(rsaKeyIn(mem, &priKey))
            break;
    }

    printf("RSA PRK found: %s", priKey.getText())

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题:这可能吗?还是有可能恢复其他秘密数据?

还是free为了安全起见,操作系统将'd内存归零?如果不是这种情况,我们应该在释放内存之前手动用零填充已分配的内存吗?

c malloc cryptography

5
推荐指数
1
解决办法
99
查看次数