In: Computer Science
A. What can happen if pointer is uninitialized. Explain the concept
and what should ideally be done
in such case
B. Memory was allocated initially for 5 elements,
later on two more elements added to list. How can
space be managed in such case. Implement the scenario in C.
A. What can happen if pointer is uninitialized. Explain the concept and what should ideally be done in such case.
An uninitialized pointer stores an undefined garbage value. The pointer would be initialized to a non-NULL garbage value that doesn't really point to anything real. An uninitialized pointer can cause a system crash.
Suppose we have declared a pointer without initializing it for example
int* ptr;
Now after this declaration we don’t know which location in memory this pointer is pointing. It might be pointing towards system stack,program’s code space or into operating system.
Now if you without initializing assign a value to it like
*ptr=50;
It can change the value at any random location towards which ptr is pointing without you knowing or giving an error which might be difficult to bug and your system might crash.
So, it is always advisable and good programming practice to initialized a pointer variable.
int* ptr = NULL;
B. Memory was allocated
initially for 5 elements, later on two more elements added to list.
How can
space be managed in such case. Implement the scenario in
C.
To handle such scenario we need to use dynamic memory allocation. It enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.
malloc()
function
reserves a block of memory of the specified number of bytes. And,
it returns a pointer of void
which can be casted into
pointers of any form.The below code can be used in demonstration.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr=NULL;
int n=0;
// Get the number of elements for the array from
user
printf("Enter number of elements: ");
scanf("%d",&n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
allocated by malloc or not
if (ptr == NULL) {
printf("Memory not
allocated.\n");
exit(0);
}
else {
// If memory is allocated then getting the elements of
the array 2,3,4, ..
printf("Memory successfully
allocated !!! \n");
for (int i = 0; i < n; ++i)
{
ptr[i] = i +
2;
}
// Print the elements of the
array
printf("The elements of the array
are: ");
for (int i = 0; i < n; ++i)
{
printf("%d ",
ptr[i]);
}
}
return 0;
}