c++: Does the new operator for dynamic allocation check for memory safety?

Quesion:
My question arises from one of my c++ exercises (from Programming Abstraction in C++, 2012 version, Exercise 12.2). Here it is:

void strcpy(char *dst, char *src) {
    while (*dst++ = *src++);
}

The definition of strcpy is dangerous. The danger stems from the fact that strcpy fails to check that there is sufficient space in the character array that receives the copy, thereby increasing the chance of a buffer-overflow error. It is possible, however, to eliminate much of the danger by using dynamic allocation to create memory space for the copied string. Write a function

char *copyCString(char *str);

that allocates enough memory for the C-style string str and then copies the characters—along with the terminating null character—into the newly allocated memory.

Here's my question: Is this new method really safe? Why it's safe? I mean, to be a little bit radical, what if there isn't enough space in the heap? Is the new operator able to check for space availability and fall in an elegant way if there isn't enough space? Will that cause other kind of "something-overflow"?


Answer:

If new fails to allocate the requested memory, it's supposed to throw a std::bad_alloc exception (but see below for more). After that, the stack will be unwound to the matching exception handler, and it'll be up to your code to figure out what to do from there.

If you really want/need to assure against an exception being thrown, there is a nothrow version of new you can use that will return a null pointer to signal failure--but this is included almost exclusively for C compatibility, and not frequently used (or useful).

For the type of situation cited in the question, you normally want to use std::string instead of messing with allocating space yourself at all.

Also note that on many modern systems, the notion of new either throwing or returning a null pointer in case of failure, is really fairly foreign. In reality, Windows will normally attempt to expand the paging file to meet your request. Linux has an "OOMKiller" process that will attempt to find "bad" processes and kill them to free up memory if you run out.

As such, even though the C++ standard (and the C standard) prescribe what should happen if allocation fails, that's rarely what happens in real life.


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值