Created
November 29, 2023 09:09
-
-
Save NotSoIntelligent/e22fd8e8f0aa6e2393e7707ab6473d79 to your computer and use it in GitHub Desktop.
A Simple repetitive Memory reallocator Function in C
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
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #define INIT_SIZE 50 | |
| #define BLK_SIZE 20 | |
| #define DBG 0 | |
| int get_string (char** str); | |
| int main () | |
| { | |
| char* str = NULL, ret = 0; | |
| str = (char*) malloc(INIT_SIZE * sizeof(char)); | |
| if (!str) { | |
| printf ("DBG: %s %d : malloc error\n", __func__, __LINE__); | |
| ret = -1; | |
| goto FAIL; | |
| } | |
| printf ("DBG: %s %d : Mem Allocated at %p \n", __func__, __LINE__, str); | |
| ret = get_string (&str); | |
| if (ret == 0) { | |
| printf ("String Got is : \n"); | |
| printf ("%s", str); | |
| } else { | |
| printf ("DBG: %s %d : Failed to get string \n", __func__, __LINE__); | |
| } | |
| FAIL: | |
| if(str) free(str); | |
| return ret; | |
| } | |
| /* Function to Get string without size of the string */ | |
| int get_string (char** str) | |
| { | |
| int i = 0, size = INIT_SIZE, len = 0, ret = 0; | |
| while (1) { | |
| #if DBG | |
| printf ("DBG: %s %d : Getting char %p \n", __func__, __LINE__, (*(str)+i)); | |
| #endif | |
| /* String entered in STDIN Buffer received in scanf one character by one */ | |
| ret = scanf ("%c", (*(str)+i)); | |
| #if DBG | |
| printf ("DBG: %s %d : Got char %c \n", __func__, __LINE__, *(*(str)+i)); | |
| #endif | |
| /* Stop getting string when EOF of new line character is reached */ | |
| if ( *(*(str)+i) == '\n' || ret == EOF ) { | |
| *(*(str)+i) = 0; //Null Character | |
| break; | |
| } | |
| i++; | |
| /* Reallocater */ | |
| if ( i >= size ) { | |
| printf ("DBG: %s %d : Reallocating\n", __func__, __LINE__); | |
| size += BLK_SIZE; | |
| *str = realloc (*str, size); | |
| if (!*str) { return -1; } | |
| printf ("DBG: %s %d : Mem Reallocated at %p \n", __func__, __LINE__, *str); | |
| } | |
| } | |
| len = strlen(*str); | |
| if (len != size) { | |
| *str = realloc (*str, len); | |
| if (!*str) { return -1; } | |
| } | |
| printf ("DBG: %s %d : size of string %d \n", __func__, __LINE__, len); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment