Q0: What is the real purpose of malloc(), realloc() and free() functions?
I have read that they enable to allocate memory in cases when the amount of memory to be allocated is unknown. But in that case, ( Q1: ) why does the function malloc() has an argument then? (if the amounf of memory is unknown)
Here is a code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 30 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else {
strcpy( description, "Zara ali a DPS student.");
}
/* suppose you want to store bigger description */
description = realloc( description, 100 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else {
strcat( description, "She is in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
/* release memory using free() function */
free(description);
}
from C Memory Management .
Q2: Can I also have a variable of different type than just chars (eg double, int)?
Q3: What is the following code? Is it allocating a memory for more variables of an array? Why do not they use the calloc() function then?
Code:
int array[10];
int * array = malloc(10 * sizeof(int));
Q4: What is the maximum number I can write inside the argument of the malloc() function?
eg can I write
Code:
char *a;
a=malloc(100000*sizeof(char));
?
Could you please help me in getting to know the dynamic memory allocation in C?
Thank you.