Ошибка Segmentation fault (core dumped)
Есть данный код на СИ, суть в том, чтобы в двумерном массиве с помощью потоков (Linux) найти самую большую последовательность чисел по возрастанию. При компиляции всё хорошо, а как запускаю программу появляется ошибка Segmentation fault (core dumped)
#include #include #include #include #include #include void random1(int arr[5][100]) < int i,j; for(i=0; i<5;i++) < for(j=0; j<100;j++) < arr[i][j]=rand()%100; printf("%d\t", arr[i][j]); >printf("\n"); > printf("\n"); > void* thread_func1(int arr[5][100])< int buffer = 1, maxbuffer=0, max=0, minElement=0, maxElement; int i,j; for(i=0;i<5;i++) < for(j=0;j<100;j++) < if(arr[i][j+1]>arr[i][j]) < buffer++; max=buffer; if(maxbuffer> if(arr[i][j+1] <=arr[i][j]) < max=buffer; if(maxbuffer buffer = 1; > > minElement = (maxElement+1)-maxbuffer; for( i = minElement; i > > int main()
Еще один пример реализации функции thread_func1, но там тоже выходит эта ошибка
void* thread_func1(int arr[5][100])< int start=0, lenght=1, max_start=0, max_lenght=0; int i,j; for(i=0;i<5;i++)< for(j=0;j<100;j++)< for(int k=j+1;k<100;k++) < if(arr[i][j]max_lenght) max_lenght= lenght, max_start=start; start = k, lenght = 1; > > > > for(i = max_start; i>>
Segmentation fault core dumped
Здравствуйте, есть задание: First получает со стандартного потока информацию о файлах каталога, и, во-первых, выводит на экран (в консоль) строки о тех из них, у которых установлен бит запуска владельцем; во-вторых, при помощи FIFO передает размер каждого из таких файлов second’у, который суммирует значения и выводит полученное значение на экран. Проблема в том, что при чтении файла в second.c возникает переполнение. first.c:
#ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #include #include #include #include #include #include #include #include #include #include #include uint64_t total_size_files(char *path) < char buf[PATH_MAX + 1], buf1[PATH_MAX + 1]; struct stat file_stats; DIR *dirp; struct dirent* dent; uint64_t sum = 0; dirp = opendir(path); if(!dirp)< perror("opendir()"); return -1; >do < dent = readdir(dirp); if(dent >0)< printf("%s - ", dent->d_name); snprintf(buf1, PATH_MAX, "%s/%s", path, dent->d_name); if(!realpath(buf1, buf)) < printf("realpath(): %s", strerror(errno)); continue; >if(!stat(buf, &file_stats))< printf("%" PRIu64 " bytes\n", (uint64_t)file_stats.st_size); sum += file_stats.st_size; >else < printf("stat(): %s\n", strerror(errno)); >>else if(dent < 0)< printf("readdir(): %s", strerror(errno)); >>while(dent); closedir(dirp); printf("Size of %ld is %" PRIu64 " bytes\n", sum); return sum; > int main() < char *path = "."; //printf("Size of %ld is %" PRIu64 " bytes\n", path, total_size_files(path)); int fd, result; uint64_t size; char resstring[1000000]; char name[]="MYFIFO.fifo"; (void)umask(0); if(mknod(name, S_IFIFO | 0666, 0) < 0)< printf("Can\'t create FIFO\n"); exit(-1); >if((result = fork()) < 0)< printf("Can\'t fork child\n"); exit(-1); >else if (result > 0) < if((fd = open(name, O_WRONLY)) < 0)< printf("Can\'t open FIFO for writing\n"); exit(-1); >size = write(fd, total_size_files(path), sizeof(uint64_t)); close(fd); printf("Parent exit\n"); close(fd); > return 0; > [\code=C] second.c:
#ifndef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #include #include #include #include #include #include #include #include #include #include #include int main() < int fd, result; size_t size; char name[]="MYFIFO.fifo"; if((fd = open(name, O_RDONLY)) < 0)< printf("Can\'t open FIFO for reading\n"); exit(-1); >size = read(fd, &result, sizeof(uint64_t)); if(size < 0)< printf("Can\'t read string\n"); exit(-1); >/* Печатаем прочитанную строку */ printf("%ld\n",size); /* Закрываем входной поток и завершаем работу */ close(fd); return 0; > [\code=C]
Qwertyr
10.02.22 19:57:45 MSK
При попытке соединения с сервером Segmentation fault (core dumped)
Доброго дня!
Начал описывать проблему в этой теме. Ситуация в следующем, есть домашний сервер OpenSUSE 15.2 Leap x86_64. Установил steamcmd, обновил. Сделал скрипт для автоматической валидации сервера cs 1.6
./steamcmd.sh +login anonymous +force_install_dir /home/steam/steamcmd/cs16 +app_update 90 validate -beta beta +quit
Запускал несколько раз обновление app_update 90 validate -beta beta, чтобы все загрузилось полностью. Запускаю сервер:
./hlds_linux -debug -game cstrike
Стартует нормально:
steam@tank:/home/steam/steamcmd/cs16> ./hlds_run -debug -game cstrike +ip 192.168.1.2 Enabling debug mode ./hlds_run: line 125: test: unlimited: integer expression expected Auto-restarting the server on crash Console initialized. Using breakpad crash handler Setting breakpad minidump AppID = 10 Forcing breakpad minidump interfaces to load Looking up breakpad interfaces from steamclient Calling BreakpadMiniDumpSystemInit Protocol version 48 Exe version 1.1.2.7/Stdio (cstrike) Exe build: 19:52:19 Aug 3 2020 (8684) STEAM Auth Server Server IP address 192.168.1.2:27015 couldn't exec listip.cfg couldn't exec banned.cfg
При попытке соединения из игры появляется сама ошибка в консоли:
./hlds_run: line 255: 7490 Segmentation fault (core dumped) $HL_CMD email debug.log to [email protected] Sun Oct 4 11:23:06 MSK 2020: Server restart in 10 seconds
В debug.log всегда 3 строчки:
---------------------------------------------- CRASH: Sun Oct 4 11:23:06 MSK 2020 Start Line: ./hlds_linux -debug -game cstrike +ip 192.168.1.2 -pidfile hlds.7475.pid End of crash report ----------------------------------------------
Теперь касаемо дампа. Я сделал все по руководству из этой темы: Как получить Dump падения HLDS.
Запускал сервер из под root, запускал еще в таком варианте:
ulimit -Hc unlimited && sudo -u steam sh -c «ulimit -Sc unlimited && whoami && ulimit -Sc && ./hlds_run -debug -game cstrike +ip 192.168.1.2»
Количество строк в debug.log так и осталось 3.
При вызове gdb по файлу дампа, система показала это:
# gdb /tmp/hlds_linux-1601800499-27814-18446744073709551615.dmp [New LWP 27814] Core was generated by `./hlds_linux -debug -game cstrike +ip 192.168.1.2 -pidfile hlds.27806.pid'. Program terminated with signal SIGSEGV, Segmentation fault. #0 0xf765b2d8 in ?? () "/tmp/hlds_linux-1601800499-27814-18446744073709551615.dmp" is a core file.
Библиотеки lib32stdc++6 установлены. SELinux disabled.
Еще меня смущает при старте сервера это сообщение:
./hlds_run: line 125: test: unlimited: integer expression expected
В 125 строке как раз идет тест ulimit
Дополню еще сообщение из dmesg
[159094.469819] hlds_linux[15779]: segfault at 0 ip 00000000f76422d8 sp 00000000ff816aa0 error 4 in engine_i486.so[f7582000+f7000] [159094.469832] Code: 11 31 c0 ba 00 00 00 01 c3 89 f6 8d bc 27 00 00 00 00 8b 82 9f 00 00 00 8b 92 a3 00 00 00 c3 8d 76 00 83 ec 1c e8 5c 62 f3 ff 10 89 04 24 ff 52 24 83 c4 1c 0f b6 c0 c3 89 f6 8d bc 27 00 00
В этой теме было размещено решение! Перейти к решению.
Последнее редактирование: 4 Окт 2020
Пользователь
DelMar
Сообщения 7 Реакции 0
Произошли чудеса, не могу понять как связаны параметры запуска сервера с лечением коры. Запустил со следующими параметрами и все полетело:
steam@tank:/home/steam/steamcmd/cs16> ./hlds_run -game cstrike -pingboost 3 +maxplayers 25 +map de_dust2 +ip 192.168.1.2 Auto-restarting the server on crash Console initialized. Using breakpad crash handler Setting breakpad minidump AppID = 10 Forcing breakpad minidump interfaces to load Looking up breakpad interfaces from steamclient Calling BreakpadMiniDumpSystemInit Protocol version 48 Exe version 1.1.2.7/Stdio (cstrike) Exe build: 19:52:19 Aug 3 2020 (8684) STEAM Auth Server Server IP address 192.168.1.2:27015 [S_API FAIL] SteamAPI_Init() failed; SteamAPI_IsSteamRunning() failed. CAppInfoCacheReadFromDiskThread took 1 milliseconds to initialize CApplicationManagerPopulateThread took 0 milliseconds to initialize (will have waited on CAppInfoCacheReadFromDiskThread) RecordSteamInterfaceCreation (PID 17741): SteamGameServer011 / GameServer RecordSteamInterfaceCreation (PID 17741): SteamUtils005 / Utils RecordSteamInterfaceCreation (PID 17741): STEAMAPPS_INTERFACE_VERSION005 / Apps RecordSteamInterfaceCreation (PID 17741): STEAMHTTP_INTERFACE_VERSION002 / HTTP RecordSteamInterfaceCreation (PID 17741): SteamNetworking005 / Networking RecordSteamInterfaceCreation (PID 17741): SteamGameServerStats001 / GameServerStats Looking up breakpad interfaces from steamclient Calling BreakpadMiniDumpSystemInit couldn't exec listip.cfg couldn't exec banned.cfg Connection to Steam servers successful. VAC secure mode is activated. ERROR: couldn't open custom.hpk. Dropped Player from server Reason: Client sent 'drop' 192.168.1.71:27005:reconnect stats CPU In Out Uptime Users FPS Players 3.00 1.82 1.47 2 2 89.73 1 status hostname: Counter-Strike 1.6 Server version : 48/1.1.2.7/Stdio 8684 secure (10) tcp/ip : 192.168.1.2:27015 map : de_dust2 at: 0 x, 0 y, 0 z players : 1 active (25 max) # name userid uniqueid frag time ping loss adr # 1 "Player" 2 STEAM_0:0:xxxxxxx 0 00:23 15 0 192.168.1.71:27005 1 users