malloc()刚刚分配的内存内容是什么? [英] What are the contents of the memory just allocated by `malloc()`?

查看:559
本文介绍了malloc()刚刚分配的内存内容是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用malloc()分配内存空间之后,我对指针到底持有什么感到好奇.联机帮助页告诉我calloc()将分配的内存空间初始化为零.

malloc()函数分配大小字节,并返回指向已分配内存的指针. 内存未初始化.如果size为0,则malloc()返回NULL或一个唯一的指针值,该值以后可以成功传递给free().​​

calloc()函数为每个大小为字节的nmemb元素数组分配内存 并返回指向已分配内存的指针. 内存设置为零.如果nmemb或 size为0,则calloc()返回NULL或以后可以使用的唯一指针值 成功传递给free().​​

我用C语言为C(haha)创建了一个非常简短的示例程序:

int main() {
    char *dynamic_chars;
    unsigned amount;
    printf("how much bytes you want to allocate?\n");
    scanf("%d", &amount);

    dynamic_chars = (char*)malloc(amount*sizeof(char));
    printf("allocated:\n%s\n", dynamic_chars);

    free(dynamic_chars);
    return 0;

}

但是,执行此代码时,它什么也不输出.如果我自己初始化内存,例如使用循环使用0xFFFF初始化每个字节,那么程序将准确显示我的期望.内存空间实际上存在,因为我不会因为声称正在尝试访问未初始化的变量而出错.

由于通常不会删除内存空间,而是将其标记为可重写,所以我想知道是否通过执行程序可以查看以前随机使用的内存字节?但是我什么也看不到,所以我对malloc()的工作方式确实感到困惑.

EDIT1

关于malloc()的另一件事,或者也许是一般的内存使用情况,这对我的程序很有趣: 如果使用calloc()分配内存,则可以通过以下方式跟踪程序的实际内存使用情况:监视它.例如,如果我告诉程序,每个calloc()分配1.000.000.000字节的内存,我将在系统监视器中看到以下内容:

时的内存消耗

您可能会想象,使用malloc()时,我什么也看不到.我知道,仅仅通过分配内存,我当时并没有真正使用它,但是我仍然对为什么我的操作系统(unix派生)无法识别它被使用感到困惑.由于malloc()就像calloc()一样,将物理地址返回到我没有得到的存储位置,因此该存储区似乎并没有被OS真正保留.另外,我可以在系统监视器中看到它,对吗? 如果我想将此作为新问题发布,请告诉我.但我认为,由于问题仍然在于malloc()的工作方式,因此它适合这里.

解决方案

否,malloc()返回未初始化的内存,其内容是不确定的.因此,尝试使用值会调用未定义行为.

引用C11,附件§J.2,未定义的行为

使用由malloc函数分配的对象的值

在这种情况下,%s需要以空值结尾的char数组.但是,dynamic_chars的内容是不确定的,因此很可能根本没有null终止符,这将导致超出范围的内存访问,进而调用UB.

引用C11,第§7.22.3.5章,malloc函数(强调我的):

malloc函数为对象的大小分配空间,该对象的大小由size其值不确定.

也就是说,请查看有关为什么不将malloc()和family的返回值转换为C的原因的讨论. /a>.

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

The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

and

The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

I created a really short example program in C, to C(haha) for myself:

int main() {
    char *dynamic_chars;
    unsigned amount;
    printf("how much bytes you want to allocate?\n");
    scanf("%d", &amount);

    dynamic_chars = (char*)malloc(amount*sizeof(char));
    printf("allocated:\n%s\n", dynamic_chars);

    free(dynamic_chars);
    return 0;

}

However when executing this code, it just outputs nothing. If I initialize the memory my self for example initializing every single byte with 0xFFFF using a loop, then the program shows me exactly what I expect. The memory space actually exists, since I wont get an error claiming that I am trying to access uninitialized variables or so.

Since memory space is usually not deleted but marked as rewritable I wonder if by executing my program, shouldn't I be able to see random previously used Bytes of memory? But I wont see anything, so I am really confused about how exactly malloc() works.

EDIT1

Another thing about malloc() or maybe memory usage in general, that is interesting about my program: If I use calloc(), to allocate memory, I can trace the actual memory usage of my program, by e.g. monitoring it. For example, if I tell my program, to allocate 1.000.000.000 Bytes of memory per calloc() I will see the following in my System monitor:

As you can probably imagine, when using malloc(), I wont see nothing. I understand, that just by allocating memory, I am not really using it at that time, but I am still confused about why my operating system (unix derivate) won't recognize it as being used. Since malloc() just like calloc() returns a physical address to a memory location I don't get, how this memory area seems to be not actually reserved by the OS. Elsewise I could see it in the System Monitor right? If I should rather post this as a new question, please let me know. But I think since the question is still about how malloc() works it fits in here.

解决方案

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..

这篇关于malloc()刚刚分配的内存内容是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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