c++ memory test

本文包含了一系列关于C++内存管理的问题,涉及new和delete操作符的使用、内存分配失败时的行为、以及不当使用内存可能导致的问题等核心概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question #1 When will this line fail to compile: new myObj[100];
a) Never
b) When myObj is too large to fit into memory
c) When myObj has no default constructor

Question #2 Assuming that myObj is less than 1000 bytes, is there anything wrong with this code?
char x[1000];
 myObj *obj = reinterpret_cast(x);
new (obj) myObj;
 a) Nope, it works fine
b) Yes, there could be byte alignment issues
c) Yes, the syntax for calling new is incorrect

Question #3 What is the functional difference between
myObj *x = new myObj[100]; delete x; and myObj *x = new myObj[100]; delete [] x;
 a) There is none; they both work as expected
b) They both do nothing.
c) The first will not invoke all myObj destructors

Question #4 What is wrong with the following code? int * x = (int *) malloc(100 * sizeof(int)); x = realloc(x, sizeof(int) * 200);
a) If realloc fails, then the original memory is lost
b) Nothing, realloc is guaranteed to succeed (by returning the original pointer)
c) Nothing, realloc frees the original memory passed to it 

Question#5 What is one possible symptom of having called free on the same block of memory twice?
a) Nothing, calling free twice on one block of memory always works fine
b) Malloc might always return the same block of memory
c) You cannot free any memory in the future 

Question#6 What's wrong with this line of code? int *x = NULL; delete x;
a) It causes a segmentation fault when delete tries to access NULL
b) Nothing
c) It is undefined behavior

Question #7 Assuming this code were being compiled using a standards-conforming C++, what is wrong with it? int * x = malloc(100 * sizeof(int)); x = realloc(x, sizeof(int) * 200);
a) malloc is undefined in C++, you can only allocate memory using new
b) Invalid cast from a void* to an int*
c) Nothing is wrong with this code

Question #8 What is the default behavior of the normal new operator failing?
 a) This is left up to the implementation to decide
b) It returns NULL
c) It throws an exception

Question #9 What is a difficulty that arises with handling out of memory errors?
a) Many cleanup operations require extra memory
b) Running out of memory rarely happens in systems that interact with users
c) Once you've run out of memory, your program cannot continue

 Question #10 What is the result of this code? myObj *foo = operator new(sizeof(foo));
a) That's not legal syntax!
b) foo has memory allocated for it, but is not constructed
c) foo has memory allocated for it, and is fully constructed
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值