I can use more memory than how much I've alloc

2019-01-01 08:52发布

char *cp = (char *) malloc(1);
strcpy(cp, "123456789");
puts(cp);

output is "123456789" on both gcc (Linux) and Visual C++ Express, does that mean when there is free memory, I can actually use more than what I've allocated with malloc()?

and why malloc(0) doesn't cause runtime error?

Thanks.

标签: c
16条回答
梦寄多情
2楼-- · 2019-01-01 09:43

It could be that you're in Debug mode, where a call to malloc will actually call _malloc_dbg. The debug version will allocate more space than you have requested to cope with buffer overflows. I guess that if you ran this in Release mode you might (hopefully) get a crash instead.

查看更多
若你有天会懂
3楼-- · 2019-01-01 09:44

No. It means that your program behaves badly. It writes to a memory location that it does not own.

查看更多
还给你的自由
4楼-- · 2019-01-01 09:47

You may be allowed to use until the memory reaches some program memory or other point at which your applicaiton will most likely crash for accessing protected memory

查看更多
孤独总比滥情好
5楼-- · 2019-01-01 09:48

When you ask malloc for 1 byte, it will probably get 1 page (typically 4KB) from the operating system. This page will be allocated to the calling process so as long as you don't go out of the page boundary, you won't have any problems.

Note, however, that it is definitely undefined behavior!

Consider the following (hypothetical) example of what might happen when using malloc:

  1. malloc(1)
  2. If malloc is internally out of memory, it will ask the operating system some more. It will typically receive a page. Say it's 4KB in size with addresses starting at 0x1000
  3. Your call returns giving you the address 0x1000 to use. Since you asked for 1 byte, it is defined behavior if you only use the address 0x1000.
  4. Since the operating system has just allocated 4KB of memory to your process starting at address 0x1000, it will not complain if you read/write something from/to addresses 0x1000-0x1fff. So you can happily do so but it is undefined behavior.
  5. Let's say you do another malloc(1)
  6. Now malloc still has some memory left so it doesn't need to ask the operating system for more. It will probably return the address 0x1001.
  7. If you had written to more than 1 byte using the address given from the first malloc, you will get into troubles when you use the address from the second malloc because you will overwrite the data.

So the point is you definitely get 1 byte from malloc but it might be that malloc internally has more memory allocated to you process.

查看更多
登录 后发表回答