释放calloc(),指针和所有位为零 [英] calloc(), pointers and all bits zero

查看:141
本文介绍了释放calloc(),指针和所有位为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  是NULL总是用C零?

C标准状态下为释放calloc下列()

的释放calloc函数nmemb个对象的数组分配空间,其每个的尺寸是尺寸。空间被初始化为所有位为零。

The calloc function allocates space for an array of nmemb objects, each of whose size is size. The space is initialized to all bits zero.

与下列警告有关的所有位为零的:

请注意,这不必是相同的浮点零或空指针常数的重新presentation

Note that this need not be the same as the representation of floating-point zero or a null pointer constant.

测试程序:

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

int main()
{
    char** list = calloc(10, sizeof(*list));
    int i;
    for (i = 0; i < 10; i++)
    {
        printf("%p is-null=%d\n", list[i], NULL == list[i]);
    }
    free(list);

    return 0;
}

我建立并执行此程序有以下编译器:

I built and executed this program with the following compilers:


  • VC7,VC8,VC9,VC10

  • GCC V4.1.2, GCC v4.3.4

  • 5.8复地,复地5.10

在所有情况下的所有位为零的是 NULL 指针(除非我做的测试程序错误)。

In all cases all bits zero is a NULL pointer (unless I made a mistake in the test program).

什么是 NULL 指针不是由C标准保证是原因的所有位为零的?出于好奇,有没有在那里的的编译器所有位为零的不是 NULL 指针?

What is the reason a NULL pointer is not guaranteed by the C standard to be all bits zero ? Out of curiousity, are there any compilers where all bits zero is not a NULL pointer ?

推荐答案

借助 com.lang.c常见问题解答这的问题5.16 时,它解释了为什么发生这种情况,和question 5.17 ,它给人以非零实际机器的例子 NULL 。相对共同的情况下是0地址是有效的,所以选择了不同的无效地址 NULL 。更深奥的例子是对符号Lisp机器,它甚至没有指针,因为我们知道他们。

The com.lang.c FAQ answers this in question 5.16, where it explains why this happens, and question 5.17, where it gives examples of actual machines with nonzero NULL. A relatively "common" case is for address 0 to be valid, so a different invalid address is selected for NULL. A more esoteric example is the Symbolics Lisp Machine, which does not even have pointers as we know them.

所以它不是真正的选择正确的编译器的问题。在一个现代化的字节寻址系统,带或不带虚拟内存,你不可能遇到一个 NULL 指针未解决0。

So it's not really a question of choosing the right compiler. On a modern byte-addressable system, with or without virtual memory, you are unlikely to encounter a NULL pointer that is not address 0.

C标准是经过精心设计,以适应硬件是彻头彻尾的离奇,而这仅仅是一个结果。沿着相同的路线另一个奇怪的小问题,就是有可能为的sizeof(无效*)!= sizeof的为(int *),但你永远不会看到它发生在字节级寻址体系结构。

The C standard is carefully designed to accommodate hardware that is downright bizarre, and this is just one the results. Another weird gotcha along the same lines is that it's possible for sizeof(void *) != sizeof(int *), but you'll never see it happen on a byte-addressable architecture.

这篇关于释放calloc(),指针和所有位为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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