Dynamic Memory

  1. T/F: Creating and maintaining dynamic data structures requires dynamic memory allocation—the ability for a program to obtain more memory space at execution time to hold new nodes, and to release space no longer needed.
  2. T/F: The following statement evaluates sizeof( struct node ) to determine the size in bytes of a structure of type struct node, allocates sizeof( struct node ) bytes in memory and stores a pointer to the allocated memory in variable newPtr.

    newPtr = malloc( sizeof( struct node ) );

  3. T/F: Function malloc returns a pointer of type void * to the memory it allocates. If it is unable to allocate memory, it returns a NULL pointer.
  4. T/F: Function free reallocates memory. It takes a number of bytes as an argument and frees that much space in memory.
  5. What causes memory leaks? What is a memory leak?
  6. Given the following data structure and a program that dynamically allocates an array of 3 objs (in the ... section), will the free function call free up all memory allocations?
    	typedef struct 
    	{
    		int *x, *y;	
    	} obj;
    	obj  *records; 
    	records = (obj *)malloc( 3 * sizeof(obj) );
    	...
    	free( records );
     
  7. Convert the code above to use calloc instead of malloc.
  8. Create a variable named values and dynamically allocate enough space for 10 integers.
  9. Create a variable named name and dynamically allocate enough space for your first name.
  10. What happens in the following code?
    	int x = 5;
    	free(x);
    	
  11. What happens in the following code?
    	int x = 5;
    	free(&x);
    	
  12. What happens when you free a non-pointer variable?
  13. What is the first thing you should do after every call to malloc/calloc?
  14. What data type is returned from a call to malloc? to calloc?
  15. What is the difference between the following two code fragments?
          scanf("%d", &number);
          p = (int *)malloc(number * sizeof(int));
    
             -and-
    
          scanf("%d", &number);
          for(i = 0; i < number; i++)
             p = (int *)malloc(sizeof(int));
    
  16. Given the following struct, show two ways to print the x value.
    	typedef struct 
    	{
    		int x, y;	
    	} obj;
    	obj  *record;
    	record = (obj *)malloc( sizeof(obj) );
    	printf( "%d\n", record->x );		// does this work?
    	printf( "%d\n", (*record)->x );		// does this work?
    	printf( "%d\n", (&record)->x );		// does this work?
    	printf( "%d\n", record.x );		// does this work?
    	printf( "%d\n", *record.x );		// does this work?
    	printf( "%d\n", (*record).x );		// does this work?
    	free( record );