diff --git a/Src/Zle/zle_main.c b/Src/Zle/zle_main.c index 1afb1bf58..d5ad893a4 100644 --- a/Src/Zle/zle_main.c +++ b/Src/Zle/zle_main.c @@ -345,11 +345,34 @@ static int kungetsz; */ /**/ -void -ungetbyte(int ch) -{ - if (kungetct == kungetsz) - kungetbuf = realloc(kungetbuf, kungetsz *= 2); +void ungetbyte(int ch) { + if (kungetbuf == NULL) { + // Initialize buffer + kungetsz = 1024; // Default initial size + kungetbuf = malloc(kungetsz * sizeof(int)); // Allocate memory + if (kungetbuf == NULL) { + fprintf(stderr, "Memory allocation failed!\n"); + return; // Exit on failure + } + kungetct = 0; // Initialize the counter + } + + if (kungetct == kungetsz) { + // Resize the buffer if it's full + int* temp = realloc(kungetbuf, kungetsz * 2 * sizeof(int)); // Try to reallocate memory + if (temp == NULL) { + fprintf(stderr, "Memory reallocation failed!\n"); + free(kungetbuf); // Free the original buffer to prevent memory leak + kungetbuf = NULL; // Nullify pointer for safety + kungetsz = 0; // Reset size + kungetct = 0; // Reset counter + return; // Exit on failure + } + kungetbuf = temp; // Update to the new buffer + kungetsz *= 2; // Update size + } + + // Add the byte to the buffer kungetbuf[kungetct++] = ch; }