What are the contents of the memory just allocated by `malloc()`?

后端 未结 3 476
时光取名叫无心
时光取名叫无心 2020-12-11 07:00

I was curious about what exactly a pointer holds, after malloc() was used to allocate memory space? The manpage tells me that calloc() initializes

相关标签:
3条回答
  • 2020-12-11 07:31

    malloc allocates the memory for you and sets pointer to it. It does not initialize the memory in any way, so the allocated memory area can contain anything. Since it does not contain a string, you can't read it's content by printing a string. Instead you could print it byte by byte, like this:

    for(int i=0;i<amount*sizeof(char);i++)
    {
        printf("%02x", (unsigned)dynamic_chars[i]);
    }
    
    0 讨论(0)
  • 2020-12-11 07:33

    It's undefined by the C language what the memory block contains when you get it. In practice it will most likely simply contain what was in that physical memory previously.

    If the memory was previously used by your program and freed you'll likely just get what was in it before. If it's memory newly requested from the operating system you'll get what the operating system put in it. Most operating systems return memory that has been specifically set to 'zero' bytes because it would be a security issue if the memory still contained what was in it from some other program previously.

    None of that is guaranteed by any standard, it's just what most systems do in practice.

    0 讨论(0)
  • 2020-12-11 07:36

    No, malloc() returns uninitialized memory, the contents of which is indeterminate. So, attempt to use the value invokes undefined behavior.

    Quoting C11, annex §J.2, Undefined behavior

    The value of the object allocated by the malloc function is used

    In this case, %s expects a null-terminated char array. However, the content of dynamic_chars is indeterminate, so there may very well be no null-terminator, at all, which will cause the out-of-bound memory access, which in turn invokes the UB.

    Quoting C11, chapter §7.22.3.5, The malloc function (emphasis mine):

    The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

    That said, please see this discussion on why not to cast the return value of malloc() and family in C..

    0 讨论(0)
提交回复
热议问题