Anda di halaman 1dari 9

Dynamic Memory Allocation

Q. What is malloc and calloc? Compare between malloc and calloc.


malloc is a subroutine for performing dynamic memory allocation in the C and C++ programming
languages. malloc is part of the standard library for both languages and is declared in the stdlib.h
header although it is also declared within the std namespace via the C++'s cstdlib header.
calloc() allocates space for an array of elements, each of which occupies sz bytes of storage. The
space of each element is initialized to binary zeros. In other words, calloc() is similar to malloc(),
except that it handles arrays of objects rather than a single chunk of storage and that it initializes the
storage allocated.
Difference
Malloc Calloc
1. malloc() takes a single argument (memory 1. calloc() needs two arguments (number of
required in bytes). variables to allocate memory, size in bytes of
a single variable).
2. malloc() does not initialize the memory 2. calloc() initializes the allocated memory to
allocated ZERO.
3. malloc()allocates byte of memory. 3. calloc() allocates block of memory.
4. If a single contiguous block cannot be 4. calloc will not fail if memory can be
allocated then malloc would fail. allocated in non-contiguous blocks when a
single contiguous block cannot be allocated.
5. syntax : 5. syntax :
void *malloc(size_t n); void *calloc(size_t n, size_t size)
returns a pointer of n bytes of unintialized returns a pointer of enough free space of
storage and returns NULL if failed array of n objects of specified size, but
initialized storage with zeros, returns NULL if
failed.

Q. Write short notes on linked list


Linked list
Linked list is a data structure in which each data item points to the next data item. This "linking" is
accomplished by keeping an address variable (a pointer) together with each data item. This pointer is
used to store the address of the next data item in the list. The structure that is used to store one
element of a linked list is called a node. A node has two parts: data and next address. The data part
contains the necessary information about the items of the list, the next address part contains the
address of the next node.

Creating Linked Lists:


A special pointer will be used to point to the first node of a linked list. We will call this pointer head.
At the beginning, when there are no nodes, head will be NULL (pointer pointing to nowhere). As soon
as there is a node in the list, head will contain the address of this first node.
A list with no nodes is called an empty list or a null list.
A NULL Pointer is used to signal the end of a list. The last node will have NULL in its next address
part.
Advantages
1. Linked List is Dynamic data Structure .
2. Linked List can grow and shrink during run time.
3. Insertion and Deletion Operations are Easier
4. Efficient Memory Utilization, i.e no need to pre-allocate memory
5. Faster Access time, can be expanded in constant time without memory overhead
6. Linear Data Structures such as Stack, Queue can be easily implemented using Linked list
Disadvantages
1. In linked list, if we want to access any node it is difficult.
2. It is occupying more memory.
3. Linked list cannot be accessed Randomly.
4. Memory is allocated to Linked List at run time if and only if there is space available in heap. If
there is insufficient space in heap then it won’t create any memory.
Q. What is static memory allocation and dynamic memory allocation?
Static Memory Allocation: Memory is allocated for the declared variable by the compiler. The
address can be obtained by using ‘address of’ operator and can be assigned to a pointer. The memory
is allocated during compile time. Since most of the declared variables have static memory, this kind of
assigning the address of a variable to a pointer is known as static memory allocation.
Dynamic Memory Allocation: Allocation of memory at the time of execution (run time) is known as
dynamic memory allocation. The functions calloc() and malloc() support allocating of dynamic
memory. Dynamic allocation of memory space is done by using these functions when value is returned
by functions and assigned to pointer variables.
Q. What is malloc and calloc? Compare between malloc and calloc.
malloc is a subroutine for performing dynamic memory allocation in the C and C++ programming
languages. malloc is part of the standard library for both languages and is declared in the stdlib.h
header although it is also declared within the std namespace via the C++'s cstdlib header.
calloc() allocates space for an array of elements, each of which occupies sz bytes of storage. The
space of each element is initialized to binary zeros. In other words, calloc() is similar to malloc(),
except that it handles arrays of objects rather than a single chunk of storage and that it initializes the
storage allocated.
Difference
Malloc Calloc
1. malloc() takes a single argument (memory 1. calloc() needs two arguments (number of
required in bytes). variables to allocate memory, size in bytes of
a single variable).
2. malloc() does not initialize the memory 2. calloc() initializes the allocated memory to
allocated ZERO.
3. malloc()allocates byte of memory. 3. calloc() allocates block of memory.
4. If a single contiguous block cannot be 4. calloc will not fail if memory can be
allocated then malloc would fail. allocated in non-contiguous blocks when a
single contiguous block cannot be allocated.
5. syntax : 5. syntax :
void *malloc(size_t n); void *calloc(size_t n, size_t size)
returns a pointer of n bytes of unintialized returns a pointer of enough free space of
storage and returns NULL if failed array of n objects of specified size, but
initialized storage with zeros, returns NULL if
failed.

Q. Write notes on free() and realloc().


realloc()
The realloc() function changes the size of a block of memory that was previously allocated with
malloc() or calloc(). The function prototype is
void *realloc(void *ptr, size_t size);
Using realloc() to increase the size of a block of dynamically allocated memory.
1: /* Using realloc() to change memory allocation. */
2:
3: #include <stdio.h>
4: #include <stdlib.h>
5: #include <string.h>
6:
7: main()
8: {
9: char buf[80], *message;
10:
11: /* Input a string. */
12:
13: puts("Enter a line of text.");
14: gets(buf);
15:
16: /* Allocate the initial block and copy the string to it. */
17:
18: message = realloc(NULL, strlen(buf)+1);
19: strcpy(message, buf);
20:
21: /* Display the message. */
22:
23: puts(message);
24:
25: /* Get another string from the user. */
26:
27: puts("Enter another line of text.");
28: gets(buf);
29:
30: /* Increase the allocation, then concatenate the string to it. */
31:
32: message = realloc(message,(strlen(message) + strlen(buf)+1));
33: strcat(message, buf);
34:
35: /* Display the new message. */
36: puts(message);
37: return(0);
38: }
Enter a line of text.
This is the first line of text.
This is the first line of text.
Enter another line of text.
This is the second line of text.
This is the first line of text.This is the second line of text.
ANALYSIS: This program gets an input string on line 14, reading it into an array of characters called
buf. The string is then copied into a memory location pointed to by message (line 19). message was
allocated using realloc() on line 18. realloc() was called even though there was no previous allocation.
By passing NULL as the first parameter, realloc() knows that this is a first allocation.
Line 28 gets a second string in the buf buffer. This string is concatenated to the string already held in
message. Because message is just big enough to hold the first string, it needs to be reallocated to
make room to hold both the first and second strings. This is exactly what line 32 does. The program
concludes by printing the final concatenated string.
free()
When we allocate memory with either malloc() or calloc(), it is taken from the dynamic memory pool
that is available to our program. This pool is sometimes called the heap, and it is finite. When our
program finishes using a particular block of dynamically allocated memory, we should deallocate, or
free, the memory to make it available for future use. To free memory that was allocated dynamically,
use free(). Its prototype is
void free(void *ptr);
The free() function releases the memory pointed to by ptr. This memory must have been allocated
with malloc(), calloc(), or realloc(). If ptr is NULL, free() does nothing.
Using free() to release previously allocated dynamic memory.
1: /* Using free() to release allocated dynamic memory. */
2:
3: #include <stdio.h>
4: #include <stdlib.h>
5: #include <string.h>
6:
7: #define BLOCKSIZE 30000
8:
9: main()
10: {
11: void *ptr1, *ptr2;
12:
13: /* Allocate one block. */
14:
15: ptr1 = malloc(BLOCKSIZE);
16:
17: if (ptr1 != NULL)
18: printf("\nFirst allocation of %d bytes successful.",BLOCKSIZE);
19: else
20: {
21: printf("\nAttempt to allocate %d bytes failed.\n", BLOCKSIZE);
22: exit(1);
23: }
24:
25: /* Try to allocate another block. */
26:
27: ptr2 = malloc(BLOCKSIZE);
28:
29: if (ptr2 != NULL)
30: {
31: /* If allocation successful, print message and exit. */
32:
33: printf("\nSecond allocation of %d bytes successful.\n", BLOCKSIZE);
34:
35: exit(0);
36: }
37:
38: /* If not successful, free the first block and try again.*/
39:
40: printf("\nSecond attempt to allocate %d bytes failed.", BLOCKSIZE);
41: free(ptr1);
42: printf("\nFreeing first block.");
43:
44: ptr2 = malloc(BLOCKSIZE);
45:
46: if (ptr2 != NULL)
47: printf("\nAfter free(), allocation of %d bytes successful.\n", BLOCKSIZE);
48:
49: return(0);
50: }
First allocation of 30000 bytes successful.
Second allocation of 30000 bytes successful.
AANALYSIS: This program tries to dynamically allocate two blocks of memory. It uses the defined
constant BLOCKSIZE to determine how much to allocate. Line 15 does the first allocation using
malloc(). Lines 17 through 23 check the status of the allocation by checking to see whether the return
value was equal to NULL. A message is displayed, stating the status of the allocation. If the allocation
failed, the program exits. Line 27 tries to allocate a second block of memory, again checking to see
whether the allocation was successful (lines 29 through 36). If the second allocation was successful, a
call to exit() ends the program. If it was not successful, a message states that the attempt to allocate
memory failed. The first block is then freed with free() (line 41), and a new attempt is made to
allocate the second block.
First allocation of 30000 bytes successful.
Second attempt to allocate 30000 bytes failed.
Freeing first block. After free(), allocation of 30000 bytes successful.
Q. Compare array and linked list.

Array Linked List


Array is a collection of elements having same Linked list is an ordered collection of elements
data type with common name. which are connected by links/pointers.
In array, elements can be accessed using In linked list, elements can’t be accessed
index/subscript value, i.e. elements can be randomly but can be accessed only
randomly accessed like arr[0], arr[3], etc. So sequentially and accessing element takes 0(n)
array provides fast and random access. time.
In array, elements are stored In linked list, elements can be stored at any
in consecutive manner in memory. available place as address of node is stored in
previous node.
Insertion & deletion takes more time in array as Insertion & deletion are fast & easy in linked list
elements are stored in consecutive memory as only value of pointer is needed to change.
locations.
In array, memory is allocated at compile time In linked list, memory is allocated at run time i.e.
i.e. Static Memory Allocation. Dynamic Memory Allocation.
Array can be single dimensional, two dimension Linked list can be singly, doubly or circular
or multidimensional. linked list.
In array, each element is independent, no In Linked list, location or address of elements is
connection with previous element or with its stored in the link part of previous element/node.
location.
In array, no pointers are used like linked list so In linked list, adjacency between the elements
no need of extra space in memory for pointer. are maintained using pointers or links, so
pointers are used and for that extra memory
space is needed.

Q. Compare between static memory allocation and dynamic memory allocation.


Static memory allocation Dynamic memory allocation
The compiler allocates the required memory space It uses functions such as malloc() or calloc() to
for a declared variable. get memory dynamically.
Using the address of operator, the reserved address If these functions are used to get memory
is obtained and this address may be assigned to a dynamically and the values returned by these
pointer variable. This way of assigning pointer value functions are assigned to pointer variables, such
to a pointer variable is known as static memory assignments are known as dynamic memory
allocation. allocation.
Memory is allocated before the execution of the Memory is allocated during the execution of the
program begins. (During Compilation) program. (During run time)
Memory size can’t be modified while execution. Memory size can be modified while execution.
Example: array Example: Linked list
Variables remain permanently allocated. Allocated only when program unit is active.
Implemented using stacks and heaps. Implemented using data segments.
Faster execution than Dynamic. Slower execution than static.
More memory Space required. Less Memory space required.

Files

Q. List the jobs performed by the fopen() and fclose() function.


fopen()
This function accepts two arguments as strings.
fopen("filename","file mode")
The first argument denotes the name of the file to be opened and the second signifies the mode in
which the file is to be opened. The second argument can be any of the following:

File Mode Description

r Open a text file for reading


w Create a text file for writing, if it exists, it is overwritten.

a Open a text file and append text to the end of the file.

rb Open a binary file for reading

wb Create a binary file for writing, if it exists, it is overwritten.

ab Open a binary file and append data to the end of the file.

fclose()
The fclose() function is used for closing opened files. The only argument it accepts is the file pointer. If
a program terminates, it automatically closes all opened files.
fclose("filename")
Q. Write the use of fprintf and fscanf functions in C language.
The fprintf and fscanf functions are identical to printf and scanf functions except that they work on
files. The first argument of theses functions is a file pointer which specifies the file to be used.
The general form of fprintf is
fprintf(fp,”control string”, list);
Where fp id is a file pointer associated with a file that has been opened for writing. The control string
is file output specifications list may include variable, constant and string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here name is an array variable of type char and age is an int variable
The general format of fscanf is
fscanf(fp,”controlstring”,list);
This statement would cause the reading of items in the control string.
Example:
fscanf(f2,”5s%d”,item,&quantity”);
Q. Write short notes on i) fgets ii) fgetc() iii) fputs and iv) fputc().
fputs is a function in C programming language that writes an array of characters to a given file
stream. fputs stands for file put string. It is included in the C standard library header file stdio.h.
The function fputs terminates after reaching terminating null character ('\0'). The null character is not
copied to the stream. The prototype of the function is as follows:
int fputs ( const char * str, FILE * stream );
The stream argument specifies the stream to which the string will be written. stdout is commonly used
here, for writing to the standard output. Otherwise, a FILE * value returned by the fopen() function is
used.
The following example is 'hello world' program using fputs:
#include <stdio.h>
int main() {
const char *buffer = "Hello world!";
fputs (buffer, stdout);
return 0;
}
fgets is a function in C programming language that reads a limited number of characters from a given
file stream source into an array of characters. fgets stands for file get string. It is included in the C
standard library header file stdio.h. The prototype of the function is as follows:
char* fgets(char *string, int length, FILE * stream);
The function terminates reading either after a new-line character is found or end-of-file is reached, or
after (length - 1) characters have been read. If a new-line was reached it is included in the string as
the last character before the null character.
The stream argument specifies the stream from which the string be read. stdin is commonly used
here, for reading from the standard input.
The following code reads characters from the console input and prints them out 20 in a line with the
puts function until an EOF occurs.
#include <stdio.h>
#define MAX_LEN 20
int main(void)
{
char str_buf[MAX_LEN + 1]; // One extra byte needed
// for the null character
while(fgets(str_buf, MAX_LEN + 1, stdin) != NULL)
puts(str_buf);
return 0;
}
fputc is a function in C programming language that writes a character specified by the
argument char to the specified stream and advances the position indicator for the stream.
If there are no errors, the same character that has been written is returned. If an error occurs, EOF is
returned and the error indicator is set.
The syntax of fputc() function is :
int fputc(int char, FILE *stream)
where
char -- This is the character to be written. This is passed as its int promotion.
stream -- This is the pointer to a FILE object that identifies the stream where the character is to be
written.
Example
#include <stdio.h>

int main ()
{
FILE *fp;
int ch;

fp = fopen("file.txt", "w+");
for( ch = 33 ; ch <= 100; ch++ )
{
fputc(ch, fp);
}
fclose(fp);

return(0);
}
If in text file file.txt has the content : we are in 2012
Then the OUTPUT is : we are in 2012
Fgetc is a function in C programming language that gets the next character from the specified
stream and advances the position indicator for the stream.
This function returns the character read as an unsigned char cast to an int or EOF on end of file or
error.
The syntax of fputc() function is :
int fgetc(FILE *stream)
where
stream -- This is the pointer to a FILE object that identifies the stream on which the operation is to
be performed.
Example
#include <stdio.h>

int main ()
{
FILE *fp;
int c;
int n = 0;

fp = fopen("file.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
}
do
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}while(1);

fclose(fp);
return(0);
}

If in text file file.txt has the content : we are in 2012


Then the OUTPUT is : we are in 2012

Anda mungkin juga menyukai