Compare commits

...

3 Commits

Author SHA1 Message Date
Michael
e9cf02e428 fix: flip decrement/increment on comparison
- this prevents wrapping size_t below 0
2026-10-13 21:11:20 +02:00
Michael
cfe3d40fc6 fix: move ownership of line to oldline
- set line to null when moved
- also, free line when loading from history
2026-10-13 21:09:18 +02:00
Michael
913449e500 fix: memory bug due to use of wrong line size 2026-10-13 21:00:05 +02:00

View File

@@ -21,7 +21,6 @@
#define DEFAULTTOKENSCAPACITY 64
#define DEFAULTHISTORYCAPACITY 128
const int LINESIZE = 512;
int cd(int argc, char** argv) {
if (argc != 1) {
@@ -143,7 +142,7 @@ int main(int argc, char** argv) {
int retval = 0;
char* line = NULL;
size_t linecapacity = 0;
char prompt[LINESIZE] = {};
char prompt[DEFAULTLINECAPACITY] = {};
size_t linelen = 0;
char* tokenwork = NULL;
size_t tokenworkcapacity = 0;
@@ -161,7 +160,7 @@ int main(int argc, char** argv) {
int laststatus = 0;
int wstatus;
char pwd[LINESIZE] = {};
char pwd[DEFAULTLINECAPACITY] = {};
char* pwd_disp;
char* user;
@@ -280,7 +279,7 @@ int main(int argc, char** argv) {
// Main loop
while(1) {
char* result = getcwd(pwd, LINESIZE - 1);
char* result = getcwd(pwd, DEFAULTLINECAPACITY - 1);
if (result == NULL) {
retval = 1;
goto cleanup;
@@ -293,7 +292,7 @@ int main(int argc, char** argv) {
snprintf(
prompt,
LINESIZE,
DEFAULTLINECAPACITY,
ANSI_BG_BLUE ANSI_FG_BLACK
"%s" // status
@@ -358,6 +357,7 @@ int main(int argc, char** argv) {
}
oldline = line;
line = NULL;
}
} else if (ansi == ANSI_CURSOR_DOWN && historyoffset > 0) {
historyoffset--;
@@ -384,6 +384,11 @@ int main(int argc, char** argv) {
if (load_from_hist == 1) {
char* historyline = history[historyi - (historyoffset)];
size_t historylinelen = strlen(historyline);
if (line != NULL) {
free(line);
}
line = malloc(historylinelen + 1);
if (line == NULL) {
retval = 1;
@@ -401,8 +406,9 @@ int main(int argc, char** argv) {
}
} else if (ansi == ANSI_DELETE_WORD) {
if (cursor > 0) {
// 0123 56
size_t index = strnrcspn(line, cursor, " \t");
memmove(line + index, line + cursor, LINESIZE - cursor);
memmove(line + index, line + cursor, linecapacity - cursor);
linelen -= cursor - index;
cursor = index;
}
@@ -423,12 +429,12 @@ int main(int argc, char** argv) {
if (cursor == linelen) {
line[cursor] = 0;
} else {
memmove(line + cursor, line + cursor + 1, LINESIZE - (cursor));
memmove(line + cursor, line + cursor + 1, linecapacity - (cursor));
}
} else {
// We are typing
if (cursor != linelen) {
memmove(line + cursor + 1, line + cursor, LINESIZE - cursor - 1);
memmove(line + cursor + 1, line + cursor, linecapacity - cursor - 1);
}
line[cursor] = readc;
@@ -478,7 +484,7 @@ int main(int argc, char** argv) {
fprintf(historyfile, "%s\n", line);
fflush(historyfile);
while (tokenworkcapacity < linelen - 1) {
while (tokenworkcapacity + 1 < linelen) {
tokenworkcapacity *= 2;
tokenwork = realloc(tokenwork, tokenworkcapacity);
}