0

Всем привет. При попытке запустить код, приведенный ниже, выводит следующую ошибку: Ошибка сегментирования (стек памяти сброшен на диск) Пытался провести отладку через gdb, но там код также не запускался, и gdb выдавал следующую ошибку:

Program received signal SIGSEGV, Segmentation fault.
__strcpy_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:298
298 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: Нет такого файла или каталога. 

Что делать?

Код:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "hacking.h" // There is the description of "fatal(...)"

#define FILENAME "/home/totalboy/notes"

int print_notes(int, int, char*); // The function of showing notes
int find_user_note(int, int); // Finding in the file for notes of user
int search_note(char*, char*); // The function of finding by keywords
void fatal(char*); // Handler critical errors

int main(int argc, char* argv[]) {
  int userid, printing = 1, fd; // fd is description of out file
  char searchstring[100] = { 0 };

  if(argv > 1) // If there are arguments
    strcpy(searchstring, argv[1]); // Then it's the string of finding
  else
    searchstring[0] = 0; // Else the string of finding is empty

  userid = getuid();

  fd = open(FILENAME, O_RDONLY); // Opening the file for only reading
  if(fd == -1)
    fatal("в функции main() при открытии файла на чтение");

  while(printing)
    printing = print_notes(fd, userid, searchstring);

  printf("------------[конец данных, касающихся заметки]------------");
  close(fd);
}

// The function of showing notes for certain uid, coinciding with the optional
// finding string
// In the end of file will be returning 0
// If there are more arguments it will be returning 1
int print_notes(int fd, int uid, char* searchstring) {
  int note_length = find_user_note(fd, uid);
  char byte = 0, note_buffer[100] = { 0 };

  if(note_length == -1) // If it's the end of the file
    return 0; // returning 0

  read(fd, note_buffer, note_length); // Reading the data of notes
  note_buffer[note_length] = 0; // The finishing of the string

  // If the finding string is discovered
  if(search_note(note_buffer, searchstring))
    printf(note_buffer); // Showing it

  return 1;
}

// The function of finding the next note for specified userID;
// It will be returning 1 with getting the end of the file
// In another way it will be returning the length of the discovered note
int find_user_note(int fd, int user_uid) {
  int note_uid = -1;
  unsigned char byte = NULL;
  int length = 0;

  while(note_uid != user_uid) { // While it's not the note for user_uid
    if(read(fd, &note_uid, 4) != 4) // Reading the data of uid
      return -1; // If 4 bytes aren't read it will be returning the file's end
    if(read(fd, &byte, 1) != 1) // Reading the symbol of the string's translate
      return -1;

    byte = length = 0;
    while(byte != '\n') { // Defining the bytes' count away from the string's end
      if(read(fd, &byte, 1) != 1) // Reading the one byte
        return -1; // If one's not read it will be returning the end of the file
      length++;
    }
  }

  lseek(fd, length * -1, SEEK_CUR); // Moving the reading position to length bytes

  printf("[DEBUG] обнаружена заметка длинной %d байтов для id %d\n", length,
    note_uid);

  return length;
}

// The function of finding notes by keyword
// It will be returning 1 if it discovered the coincidence
// It will be returning 0 in another way
int search_note(char* note, char* keyword) {
  int match = 0;
  int keyword_length = strlen(keyword);

  if(keyword_length == 0) // If there is no finding string,
    return 1;             // It always is the coincidence

  for(int i = 0; i < strlen(note); i++) { // THe note's byte-by-byte view
    if(note[i] == keyword[match]) // If the bite coincides with the keyword
      match++; // it prepares to check next byte
    else { // In another way
      if(note[i] == keyword[0]) // IF the byte coincides with the first byte of the keyword
        match = 1; // It starts the calculaction with 1
      else
        match = 0; // In another way it is 0
    }
    if(match == keyword_length) // If there is the full coincidence
      return 1; // Returning the code 1
  }
  return 0; // Returning the code 0
}

1 ответ 1

2

Даже по сообщению о segfault можно догадаться, что падение происходит в функции strcpy. А вызов strcpy у вас в коде всего один

if(argv > 1) // If there are arguments
  strcpy(searchstring, argv[1]); // Then it's the string of finding

Почему с 1 вдруг сравнивается argv, а не argc?

Язык С запрещает сравнения между указателями и целыми числами. Ваш компилятор, без сомнения, сказал вам о этом. Вы просто проигнорировали диагностические сообщения компилятора?

5
  • Господи, какая тупая ошибка. Спасибо)
    – qucals
    3 фев 2019 в 18:15
  • GCC, на удивление, ни слова про это не сказал
    – qucals
    3 фев 2019 в 18:16
  • @qucals: Не может быть. coliru.stacked-crooked.com/a/1036a618d55aab6c 3 фев 2019 в 18:17
  • ibb.co/G5xkT14
    – qucals
    3 фев 2019 в 18:19
  • @qucals: Ну так может у вас там GCC вручную настроен на подавление определенной диагностики? На godbolt мне не удалось найти версии GCC, которая бы не выдавала такой диагностики по умолчанию. 3 фев 2019 в 18:39

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.