Skip to content

Instantly share code, notes, and snippets.

@AssafTzurEl
Created June 14, 2019 08:23
Show Gist options
  • Save AssafTzurEl/437cd2bf0d817f1535caecea88f2398c to your computer and use it in GitHub Desktop.
Save AssafTzurEl/437cd2bf0d817f1535caecea88f2398c to your computer and use it in GitHub Desktop.
Memory management
#include <malloc.h>
#define MAX_STUDENTS 30
typedef struct
{
int id;
/* more fields here */
} Student;
Student *studentDb[MAX_STUDENTS] = { 0 };
Student *AddStudent(int id /* more params here */)
{
size_t index = 0;
for (; index < MAX_STUDENTS && studentDb[index]; index++)
;
studentDb[index] = malloc(sizeof(Student));
studentDb[index]->id = id;
return studentDb[index];
}
Student *DeleteStudent(int id)
{
for (size_t index = 0; index < MAX_STUDENTS; index++)
{
if (studentDb[index] && (studentDb[index]->id == id))
{
free(studentDb[index]);
studentDb[index] = NULL;
}
}
return NULL;
}
Student *GetStudent(int id)
{
for (size_t index = 0; index < MAX_STUDENTS; index++)
{
if (studentDb[index] && (studentDb[index]->id == id))
{
return studentDb[index];
}
}
return NULL;
}
void CleanStudentDb()
{
for (size_t index = 0; index < MAX_STUDENTS; index++)
{
if (studentDb[index])
{
free(studentDb[index]);
studentDb[index] = NULL;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment