如上所述,我得到了一个段。每次运行程序时都会出现故障(内核已转储)。我究竟做错了什么?我的Linux:Manjaro Linux(18.1.4 Juhraya,内核5.4.2.1-MANJARO)。
代码1(main.c):
#include <ncurses.h>
#include "setup.c"
#include "./src/write.c"
#include "./src/read.c"
int main(){
int h,w;
int c;
char message[128];
int cursorPos = 0;
initscr();
getmaxyx(stdscr, h, w);
WINDOW *win = newwin(h,w,0,0);
noecho();
keypad(stdscr, TRUE);
wborder(win,CS_BLOCK,ACS_BLOCK,ACS_BLOCK,ACS_BLOCK,ACS_BLOCK,ACS_BLOCK,ACS_BLOCK,ACS_BLOCK);
for(int i = 0; i<w; i++){
mvwaddch(win, h-3, i, ACS_BLOCK);
}
refresh();
wrefresh(win);
for(;;){
c = getch();
wmove(win, h-2, cursorPos+2);
if(c == 10){
write(message);
for(int i = 1; i<w-1; i++){
mvwaddch(win, h-2, i, ' ');
}
for (int i = 0; i < sizeof(message); i++) {
message[i] = '\0';
}
cursorPos = 0;
}else if(c == 127){
message[cursorPos] = '\0';
mvwdelch(win, h-2, cursorPos+1);
cursorPos -= 1;
}else if(c == 27){
break;
}
else{
message[cursorPos] = c;
mvwaddch(win, h-2, cursorPos+2, message[cursorPos]);
cursorPos += 1;
}
wrefresh(win);
}
endwin();
return 0;
}
代码2(write.c)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void write(char message[128]) {
FILE *fptr;
time_t rawtime;
struct tm *info;
char buffer[80];
time( &rawtime );
info = localtime( &rawtime );
strftime(buffer,80,"%x - %I:%M:%p", info);
fptr = fopen("./chat.txt", "a");
fprintf(fptr,"%s: %s\n", buffer,message);
fclose(fptr);
}
代码3(read.c)
#include <stdio.h>
void read()
{
char c;
FILE *fptr;
fptr = fopen("./chat.txt","r");
if(fptr == NULL)
{
printf("Something went wrong");
}
c = fgetc(fptr);
while(c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
}
对于这么长的帖子,我感到抱歉,但是这种细分错误确实困扰着我。感谢您的帮助。预先谢谢你!
答案 0 :(得分:1)
我建议使用valgrind
。
使用标志-ggdb3
编译代码,然后使用程序执行valgrind
。它会向您显示程序执行期间的所有无效读取和写入。不仅如此,它还会准确告诉您它们发生在哪一行以及相应的函数调用跟踪。
valgrind
的初学者,This question是一个不错的起点。