gpt4 book ai didi

C,段错误(核心转储),Linux。我能做些什么?

转载 作者:行者123 更新时间:2023-11-30 14:33:22 25 4
gpt4 key购买 nike

如上所述,我得到了一个段。每次运行程序时都会出现错误(核心转储)。我究竟做错了什么?我的 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(读取.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);
}

我对这篇长文感到抱歉,但这个段错误确实困扰着我。我很感激任何帮助。预先感谢您!

最佳答案

我建议使用valgrind

使用标志 -ggdb3 编译您的代码,然后使用您的程序执行 valgrind。它会显示程序执行期间所有无效的读取和写入。不仅如此,它还会准确地告诉您它们发生在哪一行以及相应的函数调用跟踪。

This question如果您是 valgrind 的初学者,这是一个很好的起点。

关于C,段错误(核心转储),Linux。我能做些什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59372144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com