LoginSignup
0
0

More than 5 years have passed since last update.

malloc(0) すると NULL が返ってくるものだと思い込んでいた

Last updated at Posted at 2013-07-10

malloc(0) すると NULL が返ってくるものだと思い込んでいた

実行環境(だいぶ古い)
Fedora14 32bit
x86
kernel2.6.35
libc 2.13

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

int main()
{
    int iRet = 0;
    char *pStr = NULL;

    // ===== main START =====
    pStr = malloc(0);
    printf("pStr is 0x%x \n", pStr); // DEBUG

    if ( NULL != pStr )
    {
        printf("pStr is not NULL.\n"); // DEBUG
        free(pStr);
        pStr = NULL;
        iRet = 0;
    }
    else
    {
        // pStr is NULL.
        printf("pStr is NULL.\n"); // DEBUG
        iRet = 1;
    }
    // ===== main -END- =====

    return iRet;
}
# Build
$ gcc -o e_malloc_zero malloc_zero.c
$ e_malloc_zero
pStr is 0x8c27008
pStr is not NULL.

■manpage
NULL が返ってこないこともあるよーって man にも書いてあるじゃん・・・
malloc() に渡すバイト数はちゃんとチェックしましょう

JP
http://linuxjm.sourceforge.jp/html/LDP_man-pages/man3/malloc.3.html
size が 0 の場合には、NULL もしくは free() に渡すことができるポインタが返る。

English
http://man7.org/linux/man-pages/man3/malloc.3.html

■malloc(-1) してやると NULL が返ってきた
そりゃそうだ。malloc() の引数は size_t です。
size_t ≒ unsigned int なので
malloc(-1) は malloc(4294967295U) ってことだね。
そりゃ失敗するわ・・・。

man malloc より

void *malloc(size_t size);

2014/06/27 malloc(-1) したときについての内容を修正

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0