I thought once you used free() on a memory location, that memory is returned back to memory and if you were to write to that location after it was freed, it would be undefined behavior? This is my teacher's code. Can someone please interpret what he is doing? I don't understand why he is writing to the memory that was just freed. Thankyou!
void initialize(char ***subjects, char***courses, int **CRNs, int *size)
{
int i;
*subjects = (char**) malloc (INITIAL_COURSE_SIZE * sizeof(char*));
*courses = (char**) malloc(INITIAL_COURSE_SIZE * sizeof(char*));
*CRNs = (int*) malloc(INITIAL_COURSE_SIZE * sizeof(int));
for(i = 0; i < INITIAL_COURSE_SIZE; i++)
{
(*subjects)[i] = (char*) malloc(SUBJECT_SIZE * sizeof(char));
(*courses)[i] = (char*) malloc(COURSE_SIZE * sizeof(char));
} // for i
*size = INITIAL_COURSE_SIZE;
} // initalize()
void resize(char ***subjects, char***courses, int **CRNs, int *size)
{
int i, *CRNs2, size2 = *size * 2;
char **subjects2, **courses2;
subjects2 = (char**) malloc (size2 * sizeof(char*));
courses2 = (char**) malloc(size2 * sizeof(char*));
CRNs2 = (int*) malloc(size2 * sizeof(int));
for(i = 0; i < *size; i++)
{
subjects2[i] = (*subjects)[i];
courses2[i] = (*courses)[i];
CRNs2[i] = (*CRNs)[i];
} // for i
free(*subjects); //WHY DOES HE FREE THIS??????
free(*courses);
free(*CRNs);
*subjects = subjects2;
*courses = courses2;
*CRNs = CRNs2;
for(; i < size2; i++)
{
(*subjects)[i] = (char*) malloc(SUBJECT_SIZE * sizeof(char));
(*courses)[i] = (char*) malloc(COURSE_SIZE * sizeof(char));
} // for i
*size = size2;
} // resize()
Also, if I were to do:
char **a;
a = (char*)malloc(sizeof(char*) * 100);
Does a point to the the entire array a[]? For example, a[0] and a[1]... would be char pointers. Does a point to the entire block of malloc'd char*'s or just a[0]? Thanks! I really appreciate the help!!