Last active
January 6, 2023 10:49
-
-
Save pavly-gerges/3b16fc57d1ecc55a32222a731b753dd7 to your computer and use it in GitHub Desktop.
Test Deep copy V.S. Superficial copy
This file contains hidden or 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
// 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