簡體   English   中英

在C中使用qsort和簡單的strcmp函數獲取分段錯誤?

[英]Getting segmentation fault using qsort and simple strcmp function in C?

GDB打印命令表明我的數組及其內容格式正確( 'asdf''\\00000' )但我在qsort調用中得到了一個段錯誤,它追溯到我傳遞它的比較函數。 我可以猜測的是,我以某種方式傳遞qsort一個空指針,或者我的字符串格式不正確,這對我來說似乎並非如此。

/** Word type, used to store elements of the word list,
    with room for a word of up to 20 characters. */
typedef char Word[ WORD_MAX + 1 ];

編輯:添加了Word的定義來提問^^

typedef struct {
/** Number of words in the wordlist. */
int len;
  /** Capacity of the WordList, so we can know when we need to resize. */
  int capacity;
  /** List of words.  Should be sorted lexicographically once the word list
      has been read in. */
  Word *words;
} WordList;

readWordList函數接收格式化的.txt文件:

3 the
5 hello
3 foo
... 

整數表示其后面的字符串中的字符數。 validChar只是一個布爾檢查,以查看傳入的char是否在某個范圍內。 我刪除了一些與該問題無關的代碼,例如fopen和一些初始化。

/**
 * comparison function for qsort in readWordList
 */
static int cmp(const void *p1, const void *p2){
  return strcmp(* (char * const *)  p1, * (char * const *) p2);
}

WordList *readWordList( char const *fname ){
  //malloc space for newList
  WordList *newList = ( WordList * ) malloc( sizeof( WordList ) );
  //set capacity to 10
  newList->capacity = START_CAPACITY;
...
  newList->words = ( Word * ) calloc(newList->capacity, sizeof( Word ) );
...
  while( fscanf( toRead, "%d ", &numChars ) == 1 )
  {
    //realloc space for Word *words if necessary
    if(newList->len >= newList->capacity)
    {
      newList->capacity *= 2;
      //check dereferencing
      newList->words = (Word *)realloc(newList->words, newList->capacity * sizeof(Word));
    }
    //if word is longer than 20 chars skip it
    if(numChars > WORD_MAX)
      continue;
    else
    {
      for(int i = 0; i < numChars; i++)
      {
        ch = fgetc(toRead);
          if(validChar(ch)){
            newList->words[newList->len][i] = ch;
            if(i == numChars-1){
              newList->words[(newList->len)][numChars] = '\0';
            }
          }else{
            continue;
          }
      }
      //debug
      printf("%s\n",newList->words[newList->len]);
      //increase length of wordlist
      newList->len += 1;
    }
  }
  qsort(newList->words, newList->len, sizeof(Word), cmp);
  return newList;
}

這是我的valgrind錯誤:(wordlist.c:76)指的是qsort調用;

==59199== Invalid read of size 1
==59199==    at 0x10000AAC9: _platform_strcmp (in /usr/local/Cellar/valgrind/3.11.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==59199==    by 0x100000C92: cmp (wordlist.c:23)
==59199==    by 0x1001F2BDE: _qsort (in /usr/lib/system/libsystem_c.dylib)
==59199==    by 0x100000C5E: readWordList (wordlist.c:76)
==59199==    by 0x1000007A8: main (pack.c:52)
==59199==  Address 0x656874 is not stack'd, malloc'd or (recently) free'd
==59199== 
==59199== 
==59199== Process terminating with default action of signal 11 (SIGSEGV)
==59199==  Access not within mapped region at address 0x656874
==59199==    at 0x10000AAC9: _platform_strcmp (in /usr/local/Cellar/valgrind/3.11.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==59199==    by 0x100000C92: cmp (wordlist.c:23)
==59199==    by 0x1001F2BDE: _qsort (in /usr/lib/system/libsystem_c.dylib)
==59199==    by 0x100000C5E: readWordList (wordlist.c:76)
==59199==    by 0x1000007A8: main (pack.c:52)
==59199==  If you believe this happened as a result of a stack
==59199==  overflow in your program's main thread (unlikely but
==59199==  possible), you can try to increase the size of the
==59199==  main thread stack using the --main-stacksize= flag.
==59199==  The main thread stack size used in this run was 8388608.

您的代碼執行無效的轉換: qsort會將指針傳遞給Word ,但您的cmp函數會將其視為指向char指針的const指針。

由於Word是固定大小的char數組的typedef ,因此它與指針指針不同。 您應該在cmp對指向Word的指針執行cmp ,而不是指向指針的指針:

static int cmp(const void *p1, const void *p2){
    const Word *lhs = p1;
    const Word *rhs = p2;
    return strcmp((const char*)*lhs, (const char*)*rhs);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM