fix seg fault on prompt

This commit is contained in:
Night Kaly 2024-02-10 23:31:29 +00:00
parent 3f767efaa6
commit 93979512d9
No known key found for this signature in database
GPG key ID: 8E829D3381CFEBBE
3 changed files with 22 additions and 14 deletions

View file

@ -5,7 +5,7 @@
#include "rush.h"
// color str in place
void color_text(char str[], const char *color) {
char *color_text(char *str, const char *color) {
int size = snprintf(NULL, 0, "\x1b[38;2;%sm%s\x1b[0m", color, str) + 1; // calculate size that is needed for colored string
if (size < 0) {
fprintf(stderr, "rush: snprintf failed\n");
@ -14,6 +14,5 @@ void color_text(char str[], const char *color) {
char *buf = memalloc(size);
snprintf(buf, size, "\x1b[38;2;%sm%s\x1b[0m", color, str); // format string to buf
strcpy(str, buf);
free(buf);
return buf;
}

View file

@ -5,6 +5,6 @@ const char *lavender = "174;174;255";
const char *pink = "255;210;239";
const char *blue = "137;180;250";
void color_text(char str[], const char *color);
char *color_text(char str[], const char *color);
#endif

29
rush.c
View file

@ -23,10 +23,6 @@ void *memalloc(size_t size) {
return ptr;
}
void quit_sig(int sig) {
exit(0);
}
void change_terminal_attribute(int option) {
static struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
@ -168,7 +164,7 @@ char *readline(char **paths) {
case 10: {
// enter/new line feed
if (buf_len == 0) {
break;
return NULL;
}
// check if command includes !!
if (strstr(buffer, "!!") != NULL) {
@ -450,16 +446,23 @@ void command_loop(char **paths) {
}
char time[256];
strcpy(time, timestr);
color_text(time, lavender); // lavender colored time string
char *modtime = memalloc(sizeof(char) * 256);
modtime = color_text(time, lavender); // lavender colored time string
char *cwd = memalloc(sizeof(char) * (PATH_MAX + 2));
sprintf(cwd, "[%s]", cwdstr);
color_text(cwd, pink); // pink colored current directory
char arrow[32] = "»";
color_text(arrow, blue);
printf("%s %s %s ", time, cwd, arrow);
cwd = replace_absolute_home(cwd);
cwd = color_text(cwd, pink); // pink colored current directory
char *arrow = memalloc(sizeof(char) * 32);
strcpy(arrow, "»");
arrow = color_text(arrow, blue);
printf("%s %s %s ", modtime, cwd, arrow);
cmd_count = 0; // upward arrow key resets command count
line = readline(paths);
if (line == NULL) {
printf("\n");
continue;
}
save_command_history(line);
bool has_pipe = false;
for (int i = 0; line[i] != '\0'; i++) {
@ -482,10 +485,16 @@ void command_loop(char **paths) {
free(args);
}
free(line);
free(modtime);
free(cwd);
free(arrow);
};
}
void quit_sig(int sig) {
exit(EXIT_SUCCESS);
}
int main(int argc, char **argv) {
// setup
signal(SIGINT, quit_sig);