题目
题目

DD2360/FDD3360 HT25 (appgpu25) Quiz 1: Basic knowledge

判断题

Inside the main() function of "particletest.c", we have now allocated an array of 1024 particles of type Particle. As we would like this number to be flexible in the future, the array is allocated dynamically using malloc(), which is part of the C Standard General Utilities Library. Our implementation uses the following approach: #include <stdio.h> #include <stdlib.h> #define NUM_PARTICLES 1024 ··· int main() { Particle *particles = (Particle *)malloc(NUM_PARTICLES); ··· } Despite the fact that the declaration seems correct, the code produces a segmentation fault exception in some experiments. However, in some other situations, no apparent errors are produced. Do you consider the declaration and allocation to be correct (and, thus, the error located somewhere else in the source code)?

选项
A.True
B.False
查看解析

查看解析

标准答案
Please login to view
思路分析
Question restatement: The code allocates an array of 1024 Particle objects using malloc, with the line Particle *particles = (Particle *)malloc(NUM_PARTICLES); inside main. The true/false claim to evaluate is whether the declaration and allocation are correct. Option 1: True. Why this is not correct: The expression malloc(NUM_PARTICLES) allocates NUM_PARTICLES bytes, not NUM_PARTICLES times the size of a Particle object. Since a Particle is likely larger than 1 byte, this results in under-allocation for an array of 1......Login to view full explanation

登录即可查看完整答案

我们收录了全球超50000道考试原题与详细解析,现在登录,立即获得答案。

类似问题

更多留学生实用工具

加入我们,立即解锁 海量真题独家解析,让复习快人一步!