Saturday, 25 February 2017

GATE EXAM PREPARATION IN "C" - Dynamic Memory Allocation

#include<stdio.h>
int main()
{
    int *p = (int *)malloc(sizeof(int));

    p = NULL;

    free(p);
}
Run on IDE
(A) Compiler Error: free can’t be applied on NULL pointer
(B) Memory Leak
(C) Dangling Pointer
(D) The program may crash as free() is called for NULL pointer.


Answer: (B) 

Explanation: free() can be called for NULL pointer, so no problem with free function call.
The problem is memory leak, p is allocated some memory which is not freed, but the pointer is assigned as NULL. The correct sequence should be following:
    free(p);
    p = NULL;

GATE EXAM PREPARATION IN "C" - Dynamic Memory Allocation

Which of the following is/are true
(A) calloc() allocates the memory and also initializes the allocates memory to zero, while memory allocated using malloc() has random data.
(B) malloc() and memset() can be used to get the same effect as calloc().
(C) calloc() takes two arguments, but malloc takes only 1 argument.
(D) Both malloc() and calloc() return ‘void *’ pointer.
(E) All of the above


Answer: (E) 

Explanation: All of the given options are true.

GATE EXAM PREPARATION IN "C" - dynamic-memory-allocation/

# include<stdio.h>
# include<stdlib.h>
 
void fun(int *a)
{
    a = (int*)malloc(sizeof(int));
}
 
int main()
{
    int *p;
    fun(p);
    *p = 6;
    printf("%d\n",*p);
    return(0);
}

(A) May not work
(B) Works and prints 6


Answer: (A)

Explanation: The program is not valid. Try replacing “int *p;” with “int *p = NULL;” and it will try to dereference a null pointer.
This is because fun() makes a copy of the pointer, so when malloc() is called, it is setting the copied pointer to the memory location, not p. p is pointing to random memory before and after the call to fun(), and when you dereference it, it will crash.
If you want to add memory to a pointer from a function, you need to pass the address of the pointer (ie. double pointer).

Consider the following three C functions :GATE EXAM PREPARATION IN "C" (GATE 2001)


[PI] int * g (void)
{
  int x= 10;
  return (&x);
}
 
[P2] int * g (void)
{
  int * px;
  *px= 10;
  return px;
}
 
[P3] int *g (void)
{
  int *px;
  px = (int *) malloc (sizeof(int));
  *px= 10;
  return px;
}

Which of the above three functions are likely to cause problems with pointers?
(A) Only P3
(B) Only P1 and P3
(C) Only P1 and P2
(D) P1, P2 and P3


Answer: (C)

Explanation: In P1, pointer variable x is a local variable to g(), and g() returns pointer to this variable. x may vanish after g() has returned as x exists on stack. So, &x may become invalid.
In P2, pointer variable px is being assigned a value without allocating memory to it.
P3 works perfectly fine. Memory is allocated to pointer variable px using malloc(). So, px exists on heap, it’s existence will remain in memory even after return of g() as it is on heap.

(GATE CS 2000)dynamic-memory-allocation


X: m=malloc(5); m= NULL;        1: using dangling pointers
Y: free(n); n->value=5;         2: using uninitialized pointers
Z: char *p; *p = ’a’;           3. lost memory is:
(A) X—1 Y—3 Z-2
(B) (X—2 Y—1 Z-3
(C) X—3 Y—2 Z-1
(D) X—3 Y—1 Z-2


Answer: (D)

Explanation: X -> A pointer is assigned to NULL without freeing memory so a clear example of memory leak
Y -> Trying to retrieve value after freeing it so dangling pointer.
Z -> Using uninitialized pointers

What is volatile keyword?


The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler.
Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. See Understanding “volatile” qualifier in C for more details.
Can a variable be both const and volatile?
yes, the const means that the variable cannot be assigned a new value. The value can be changed by other code or pointer. For example the following program works fine.
int main(void)
{
    const volatile int local = 10;
    int *ptr = (int*) &local; 
    printf("Initial value of local : %d \n", local); 
    *ptr = 100; 
    printf("Modified value of local: %d \n", local); 
    return 0;
}

How will you print numbers from 1 to 100 without using loop?

How will you print numbers from 1 to 100 without using loop?

We can use recursion for this purpose.
/* Prints numbers from 1 to n */
void printNos(unsigned int n)
{
  if(n > 0)
  {
    printNos(n-1);
    printf("%d ",  n);
  }
}

What are static functions? What is their use?


Ans:In C, functions are global by default. The “static” keyword before a function name makes it static. Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other file

What are local static variables? What is their use?


Ans:A local static variable is a variable whose lifetime doesn’t end with a function call where it is declared. It extends for the lifetime of complete program. All calls to the function share the same copy of local static variables. Static variables can be used to count the number of times a function is called. Also, static variables get the default value as 0. For example, the following program prints “0 1″
#include <stdio.h>
void fun()
{
    // static variables get the default value as 0.
    static int x;
    printf("%d ", x);
    x = x + 1;
}

int main()
{
    fun();
    fun();
    return 0;
}
// Output: 0 1

What is memory leak? Why it should be avoided


Ans: Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
/* Function with memory leak */
#include <stdlib.h>
 
void f()
{
   int *ptr = (int *) malloc(sizeof(int));
 
   /* Do some work */
 
   return; /* Return without freeing ptr*/
}

What is Dangling pointer?


Ans: Dangling Pointer is a pointer that doesn’t point to a valid memory location. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. Following are examples.


// EXAMPLE 1
int *ptr = (int *)malloc(sizeof(int));
.............
.............
free(ptr);

// ptr is a dangling pointer now and operations like following are invalid
*ptr = 10;  // or printf("%d", *ptr);



// EXAMPLE 2
int *ptr = NULL
{
   int x  = 10;
   ptr = &x;
}
// x goes out of scope and memory allocated to x is free now.
// So ptr is a dangling pointer now.

GATE EXAM PREPARATION IN "C" - What is scope of a variable? How are variables scoped in C?

What is scope of a variable? How are variables scoped in C?

Ans: Scope of a variable is the part of the program where the variable may directly be accessible. In C, all identifiers are lexically (or statically) scoped. 

What are different storage class specifiers in C?

auto, register, static, extern

What is the difference between declaration and definition of a variable/function


 Declaration of a variable/function simply declares that the variable/function exists somewhere in the program but the memory is not allocated for them. But the declaration of a variable/function serves an important role. And that is the type of the variable/function. Therefore, when a variable is declared, the program knows the data type of that variable. In case of function declaration, the program knows what are the arguments to that functions, their data types, the order of arguments and the return type of the function. So that’s all about declaration. Coming to the definition, when we define a variable/function, apart from the role of declaration, it also allocates memory for that variable/function. Therefore, we can think of definition as a super set of declaration. (or declaration as a subset of definition). From this explanation, it should be obvious that a variable/function can be declared any number of times but it can be defined only once. (Remember the basic principle that you can’t have two locations of the same variable/function).

   // This is only declaration. y is not allocated memory by this statement 
  extern int y; 

  // This is both declaration and definition, memory to x is allocated by this statement.
  int x;

GATE EXAM PREPARATION IN "C" - Pointer Basics

Output of following program?
# include <stdio.h>
void fun(int *ptr)
{
    *ptr = 30;
}

int main()
{
  int y = 20;
  fun(&y);
  printf("%d", y);

  return 0;
}
(A) 20
(B) 30
(C) Compiler Error
(D) Runtime Error


Answer: (B) 

Explanation: The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value at the address ptr. The dereference operator * is used to access the value at an address. In the statement ‘*ptr = 30’, value at address ptr is changed to 30. The address operator & is used to get the address of a variable of any data type. In the function call statement ‘fun(&y)’, address of y is passed so that y can be modified using its address.

GATE EXAM PREPARATION IN "C" - Functions

#include <stdio.h>
#include <stdarg.h>
int fun(int n, ...)
{
    int i, j = 1, val = 0;
    va_list p;
    va_start(p, n);
    for (; j < n; ++j)
    {
        i = va_arg(p, int);
        val += i;
    }
    va_end(p);
    return val;
}
int main()
{
    printf("%d\n", fun(4, 1, 2, 3));
    return 0;
}

(A) 3
(B) 5
(C) 6
(D) 10


Answer: (C) 

Explanation: The function receives variable number of arguments as there are three dots after first argument.   The firs argument is count of all arguments including first.  The function mainly returns sum of all remaining arguments. 

GATE EXAM PREPARATION IN "C" - In C, what is the meaning of following function prototype with empty parameter list


void fun()
{
   /* .... */
}
Run on IDE
(A) Function can only be called without any parameter
(B) Function can be called with any number of parameters of any types
(C) Function can be called with any number of integer parameters.
(D) Function can be called with one integer parameter.


Answer: (B) 

Explanation: Empty list in C mean that the parameter list is not specified and function can be called with any parameters. In C, to declare a function that can only be called without any parameter, we should use “void fun(void)”
As a side note, in C++, empty list means function can only be called without any parameter. In C++, both void fun() and void fun(void) are same.

What is the meaning of using static before function declaration?


For example following function sum is made static
static int sum(int x, int y, int z)
{
    return (x + y + z);
}
(A) Static means nothing, sum() is same without static keyword.
(B) Function need not to be declared before its use
(C) Access to static functions is restricted to the file where they are declared
(D) Static functions are made inline


Answer: (C)

Explanation: In C, functions are global by default. Unlike global functions, access to static functions is restricted to the file where they are declared. We can have file level encapsulation using static variables/functions in C because when we make a global variable static, access to the variable becomes limited to the file in which it is declared.

GATE EXAM PREPARATION IN "C" - What is the meaning of using extern before function declaration?


For example following function sum is made extern
extern int sum(int x, int y, int z)
{
    return (x + y + z);
}
(A) Function is made globally available
(B) extern means nothing, sum() is same without extern keyword.
(C) Function need not to be declared before its use
(D) Function is made local to the file.


Answer: (B) 

Explanation: extern keyword is used for global variables. Functions are global anyways, so adding extern doesn’t add anything.

GATE EXAM PREPARATION IN "C" - FUNCTIONS

#include <stdio.h>
int main()
{
  printf("%d", main);  
  return 0;
}

(A) Address of main function
(B) Compiler Error
(C) Runtime Error
(D) Some random value


Answer: (A) 

Explanation: Explanation: Name of the function is actually a pointer variable to the function and prints the address of the function. Symbol table is implemented like this.
struct
{
   char *name;
   int (*funcptr)();
}
symtab[] = {
   "func", func,
   "anotherfunc", anotherfunc,
};

Which of the following is true about return type of functions in C?


(A) Functions can return any type
(B) Functions can return any type except array and functions
(C) Functions can return any type except array, functions and union
(D) Functions can return any type except array, functions, function pointer and union


Answer: (B) 

Explanation: In C, functions can return any type except arrays and functions. We can get around this limitation by returning pointer to array or pointer to function.

GATE EXAM PREPARATION IN "C" - FUNCTIONS

#include <stdio.h>
int main()
{
    int i = 5;
    printf("%d %d %d", i++, i++, i++);
    return 0;
}

(A) 7 6 5
(B) 5 6 7
(C) 7 7 7
(D) Compiler Dependent


Answer: (D) 

Explanation: When parameters are passed to a function, the value of every parameter is evaluated before being passed to the function.
What is the order of evaluation of parameters – left-to-right or right-to-left?
If evaluation order is left-to-right, then output should be 5 6 7 and if the evaluation order is right-to-left, then output should be 7 6 5. Unfortunately, there is no fixed order defined by C standard. A compiler may choose to evaluate either from left-to-right.
So the output is compiler dependent.

GATE EXAM PREPARATION IN "C" - STRING

What does the following fragment of C-program print?
char c[] = "GATE2011"; 
char *p =c; 
printf("%s", p + p[3] - p[1]) ;

(A) GATE2011
(B) E2011
(C) 2011
(D) 011


Answer: (C) 

Explanation: See comments for explanation.

char c[] = "GATE2011"; 

 // p now has the base address string "GATE2011" 
char *p = c;  

// p[3] is 'E' and p[1] is 'A'. 
// p[3] - p[1] = ASCII value of 'E' - ASCII value of 'A' = 4 
// So the expression  p + p[3] - p[1] becomes p + 4 which is 
// base address of string "2011" 
printf("%s", p + p[3] - p[1]);  // prints 2011

GATE EXAM PREPARATION IN "C" -macro-preprocessor

#include <stdio.h>
#define square(x) x*x
int main()
{
  int x;
  x = 36/square(6);
  printf("%d", x);
  return 0;
}

(A) 1
(B) 36
(C) 0
(D) Compiler Error


Answer: (B) 

Explanation: Preprocessor replaces square(6) by 6*6 and the expression becomes x = 36/6*6 and value of x is calculated as 36. Note that the macro will also fail for expressions “x = square(6-2)”
If we want correct behavior from macro square(x), we should declare the macro as
#define square(x) ((x)*(x))  

GATE EXAM PREPARATION IN "C" - macro-preprocessor

#include <stdio.h>
#if X == 3
    #define Y 3
#else
    #define Y 5
#endif

int main()
{
    printf("%d", Y);
    return 0;
}

What is the output of the above program?
(A) 3
(B) 5
(C) 3 or 5 depending on value of X
(D) Compile time error


Answer: (B) 

Explanation: In the first look, the output seems to be compile-time error because macro X has not been defined. In C, if a macro is not defined, the pre-processor assigns 0 to it by default. Hence, the control goes to the conditional else part and 5 is printed. See the next question for better understanding.