Skip to main content

Memory Allocation & Structs

Dynamic Memory Allocation

c++ uses the keyword new to perform dynamic memory allocation

c uses the malloc() function in stdlib to achieve dynamic memory allocation

#include <stdlib.h>
// malloc return a pointer to the space allocated
void * malloc(int size); // size specify number of byte of memory needed

Request Memory

#include <stdio.h>
#include <stdlib.h>
int main() {
int size = 5;
int *a;
a = (int*) malloc (size * sizeof(int))
}

explanation:

  • (Int*) is required to cast the return of malloc as the pointer return by malloc is type void
  • sizeof(data type) get the number of byte needed for a particular data type

Release Memory

// pass in a pointer value returned by malloc() to free memory
void free(void *ptr);

Struct

c do not have classes, only can use struct which have no acess control

c structs do not support member functions, do not have constructor/ destructor

typedef

create an alias to treat provided name as "struct structname"

#include <stlib.h>
#include <stdio.h>
struct person {
int age;
char name[20];
}
typedef struct person Person;
int main() {
Person a;
// or struct person a;
}