C Interview Questions Part 17

Q:What is the difference between "calloc(...)" and "malloc(...)"?
A:1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size). malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).
2. malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available calloc(...) allocates an array in memory with elements initialized to and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to set the new handler mode.

Q:What is the difference between "printf(...)" and"sprintf(...)"?
A:sprintf(...) writes data to the character array whereas printf(...) writes data to the
standard output device.

Q:What does static variable mean?

A:There are 3 main uses for the static.
1. If you declare within a function:It retains the value between function calls
2.If it is declared for a function name:By default function is extern..so it will be visible from other files if the function declaration is as static..it is invisible for the outer files
3. Static for global variables:By default we can use the global variables from outside files If it is static global..that variable is limited to with in the file
 

Q:What are the differences between malloc() and calloc()?
A:There are 2 differences.First, is in the number of arguments. malloc() takes a single argument(memory required in bytes), while calloc() needs 2 arguments(number of variables to allocate memory, size in bytes of a
single variable).Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.
 

Q:Difference between const char* p and char const* p?
A:In const char* p, the character pointed by ‘p’ is constant, so u cant change the value of character pointed by p but u can make ‘p’ refer to some other location. in char const* p, the ptr ‘p’ is constant not the character referenced by it, so u cant make ‘p’ to reference to any other location but u can change the value of the char pointed by ‘p’.

Q:How can you determine the size of an allocated portion of memory?

A:You can’t, really. free() can , but there’s no way for your program to know the trick free() uses. Even if you disassemble the library and discover the trick, there’s no guarantee the trick won’t change with the next release of the compiler.