Skip to content

Instantly share code, notes, and snippets.

@Scrappers-glitch
Created September 19, 2023 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Scrappers-glitch/312346e1bba33fc88fa160b7302acf1d to your computer and use it in GitHub Desktop.
Save Scrappers-glitch/312346e1bba33fc88fa160b7302acf1d to your computer and use it in GitHub Desktop.
Example for freeing buffer cells of a pointer to a pointer
// Online C compiler to run C program online
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static inline void freeBufferCells(void** buffer, int count) {
for (int i = 0; i < count; i++) {
free(buffer[i]);
buffer[i] = NULL;
}
}
int main() {
void** ptr = (void**) calloc(1, sizeof(void**));
char* str0 = (char*) calloc(22, sizeof(char));
char* str1 = (char*) calloc(22, sizeof(char));
char* str2 = (char*) calloc(22, sizeof(char));
ptr[0] = str0;
ptr[1] = str1;
ptr[2] = str2;
// Write C code here
strcat(ptr[0], "hello");
strcat(ptr[1], "world");
strcat(ptr[2], "bye");
printf("%s\n", ptr[0]);
printf("%s\n", ptr[1]);
printf("%s\n", ptr[2]);
freeBufferCells(ptr, 3);
printf("%s\n", str0);
printf("%s\n", str1);
printf("%s\n", str2);
return 0;
}
@Scrappers-glitch
Copy link
Author

Scrappers-glitch commented Sep 19, 2023

Output:

hello
world
bye

�b��
�b��

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment