Skip to content

Instantly share code, notes, and snippets.

@pavly-gerges
Last active January 6, 2023 10:49
Show Gist options
  • Save pavly-gerges/3b16fc57d1ecc55a32222a731b753dd7 to your computer and use it in GitHub Desktop.
Save pavly-gerges/3b16fc57d1ecc55a32222a731b753dd7 to your computer and use it in GitHub Desktop.
Test Deep copy V.S. Superficial copy
// Online C compiler to run C program online
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
typedef struct {
int baud;
uint8_t data;
} uart;
void destroy(uart* bus) {
bus->data = 0;
bus->baud = 0;
}
int main() {
/* original pointer */
uart* uart_bus = (uart*) calloc(1, sizeof(void));
uart_bus->baud = 0xFF;
uart_bus->data = 6;
/* superficial/shallow copy */
uart* shallow = uart_bus;
printf("%p\n", uart_bus);
printf("%p\n", shallow);
/* deep copy */
uart* copy = (uart*) calloc(1, sizeof(void));
copy->baud = uart_bus->baud;
copy->data = uart_bus->data;
printf("%p\n", uart_bus);
printf("%p\n", copy);
/* test delete on superficial v.s. deep copies */
destroy(uart_bus);
printf("%i\n", shallow->data); /* output: 0 */
printf("%i\n", copy->data); /* output: 6 */
free(uart_bus);
free(shallow); /* free(): double free detected in tcache 2 */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment