Memory Allocation Interview Questions

Memory Allocation Interview Questions
1.Why doesn’t the code “char *answer; gets(answer);” work?
A:The pointer variable “answer” has not been set to point to any
valid storage. The simplest way to correct this fragment is to use
a local array, instead of a pointer.

2.I can’t get strcat to work. I tried “char *s1 = “Hello, “,
*s2 = “world!”, *s3 = strcat(s1, s2);” but I got strange results.

A:Again, the problem is that space for the concatenated result is not
properly allocated.

3.But the man page for strcat says that it takes two char *’s as
arguments. How am I supposed to know to allocate things?

A:In general, when using pointers you _always_ have to consider
memory allocation, at least to make sure that the compiler is doing
it for you.

4.You can’t use dynamically-allocated memory after you free it, can
you?

A:No. Some early man pages implied otherwise, but the claim is no
longer valid.

5.How does free() know how many bytes to free?
A:The malloc/free package remembers the size of each block it
allocates and returns.

6.Is it legal to pass a null pointer as the first argument to
realloc()?

A:ANSI C sanctions this usage, but several earlier implementations do
not support it.

7.Is it safe to use calloc’s zero-fill guarantee for pointer and
floating-point values?

A:No.

8.What is alloca and why is its use discouraged?
A:alloca allocates memory which is automatically freed when the
function which called alloca returns. alloca cannot be written
portably, is difficult to implement on machines without a stack,
and fails under certain conditions if implemented simply.

No comments: