- 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.
- 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 ) );
- 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.
- T/F: Function free reallocates memory. It takes a number of bytes as an argument and frees that much space in memory.
- What causes memory leaks? What is a memory leak?
- 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 );
- Convert the code above to use calloc instead of malloc.
- Create a variable named values and dynamically allocate enough space for 10 integers.
- Create a variable named name and dynamically allocate enough space for your first name.
- What happens in the following code?
int x = 5;
free(x);
- What happens in the following code?
int x = 5;
free(&x);
- What happens when you free a non-pointer variable?
- What is the first thing you should do after every call to malloc/calloc?
- What data type is returned from a call to malloc? to calloc?
- 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));
- 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 );