#include <stdlib.h>
void *malloc(size_t size);
void exemple(void)
{
char *string;
string = malloc(sizeof(char) * 5);
if (string == NULL)
return;
string[0] = 'H';
string[1] = 'e';
string[2] = 'y';
string[3] = '!';
string[4] = ' ';
printf("%s
", string);
free(string);
}
/// output : "Hey!"
<stdlib.h>
adds specified amount of memory but there could be more writable memory ahead, so you have to decide how much you access
#include <stdlib.h>
int main(){
int *ptr;
ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */
if (ptr != NULL) {
*(ptr + 5) = 480; /* assign 480 to sixth integer */
printf("Value of the 6th integer is %d",*(ptr + 5));
}
}
Example: ptr = (int *) malloc (50)
int* a =(int*)malloc(sizeof(int))
// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
// Let's allocate enough space on the heap for an array storing 4 ints
intArray = (int *) malloc(4 * sizeof(int)); // A pointer to an array of ints
intArray[0] = 10;
intArray[1] = 20;
intArray[2] = 25;
intArray[3] = 35;
int main(int argc, char *argv[])
{
int* memoireAllouee = NULL;
memoireAllouee = malloc(sizeof(int));
if (memoireAllouee == NULL) // Si l'allocation a échoué
{
exit(0); // On arrête immédiatement le programme
}
// On peut continuer le programme normalement sinon
return 0;
}
In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.
ptr = (cast_type *) malloc (byte_size);
int cp(void)
{
char *s;
s = malloc(12);
strcpy(s, "Best School");
return (0);
}