Created
September 19, 2023 22:24
-
-
Save pavly-gerges/312346e1bba33fc88fa160b7302acf1d to your computer and use it in GitHub Desktop.
Example for freeing buffer cells of a pointer to a pointer
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 <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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: