Created
June 14, 2019 08:23
-
-
Save AssafTzurEl/437cd2bf0d817f1535caecea88f2398c to your computer and use it in GitHub Desktop.
Memory management
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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