The malloc() function is defined in the stdlib.h header file. It helps to allocate the specified memory and returns a pointer to it. The malloc() function can't set allocated memory to zero.
void *malloc(size_t size); #where sizes hould be in bytes
The malloc() function takes two parameters. This function helps to allocate memory blocks dynamically. We can assign the malloc function to any pointer.
Parameter | Description | Required / Optional |
---|---|---|
size | This is the size of the memory block, in bytes | Required |
The return value of malloc() function is a pointer to the allocated memory.
Input | Return Value |
---|---|
success | pointer to memory |
fails | NULL |
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *s;
/*memory allocation */
s = (char *) malloc(12);
strcpy(s, "programming");
printf("String = %s, Address = %u\n", s, s);
/* Reallocating memory */
s = (char *) realloc(s, 20);
strcat(s, ".com");
printf("String = %s, Address = %u\n", s, s);
free(s);
return(0);
}
Output:
String = programming, Address = 355090448 String = programming.com, Address = 355090448
#include <stdio.h>
#include <stdlib.h>
int main (){
int *p;
p = malloc(15 * sizeof(*p));
if (p != NULL) {
*(p + 5) = 480;
printf("6th integer value is %d",*(p + 5));
}
}
Output:
6th integer value is 480