Copying Pointers vs Copying Objects
In this activity we’re going to explore the difference between copying pointers vs copying objects. This is important for a few reasons. Not the least of which is because you will then know what needs free-ing and what doesn’t.
For these questions, it might be helpful to draw out what is on the stack vs. what is on the heap.
Snippet 1:
#include <stdlib.h>
int main(){
int a = 5;
int *a_ptr = &a;
}Question: Do we need to write free(a_ptr);?
Snippet 2:
#include <stdlib.h>
int main(){
int *b = calloc(5, sizeof(int));
int *b_ptr = b;
free(b);
}Question: Do we need to write free(b_ptr);?
Snippet 3:
#include <stdlib.h>
#include <string.h>
int main(){
char *s = calloc(5, sizeof(char));
char *s_ptr = strndup(s, 5);
free(s);
}Question: Do we need to write free(s_ptr);?
It might be helpful to check man strndup.
Snippet 4:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char **p = calloc(2, sizeof(char *));
size_t n = 0;
getline(&p[0], &n, stdin);
n = 0;
getline(&p[1], &n, stdin);
char **q = calloc(2, sizeof(char *));
q[0] = p[0];
q[1] = p[1];
free(p[0]);
free(p[1]);
free(p);
}Question: Do we need to write free(q);? What about free(q[0])? What about free(q[1])?
Snippet 5:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char **p = calloc(2, sizeof(char *));
size_t n = 0;
getline(&p[0], &n, stdin);
n = 0;
getline(&p[1], &n, stdin);
char **q = calloc(2, sizeof(char *));
q[0] = strdup(p[0]); // the difference
q[1] = strdup(p[1]); // the difference
free(p[0]);
free(p[1]);
free(p);
}Question: Do we need to write free(q);? What about free(q[0])? What about free(q[1])?
Activity 2
We will spend in lab time showing how to solve the PE questions.
Download the PE1 question paper (PDF).
Use the
cs1010menu to download your own copy once it is available:
choose Download CS1010 content, then Practical Exam Practice, then PE-1-With-Private-TCs.
Confirm your GitHub username and download location.
In each question’s folder, editstudent.c, runmaketo compile,
and runmake testto run the public and private tests.
Use Submit current work in thecs1010menu to save your changes online.