【问题标题】:Segmentation fault (core dump)?分段错误(核心转储)?
【发布时间】:2021-06-03 15:11:44
【问题描述】:

我正在尝试使用标头 tokenizer.h 文件访问 tokenizer.c 中的方法,但是当我向安慰。 我试过重新排列指针和内存分配,我也得到了同学的帮助。我仍然收到错误消息。

#include <stdio.h>
#include <stdlib.h>
#include "tokenizer.h"
#include "history.h"

int main(){
  int noexit = 1;
  while(noexit){
    char input[100];
    printf("> ");

    fgets(input, 100, stdin);

    if(*input == '0'){
      noexit = 0;
    }
    else{
      char** tokens = tokenize(input);
      print_tokens(tokens);
      free_tokens(tokens);
    }
  }
  //past output
  /*printf(space_char(' '));*/
}

这是我的主要方法,在文件 uimain.c 中。这还没有完成,但只有当我删除了

char** tokens = tokenize(input);
      print_tokens(tokens);
      free_tokens(tokens);

阻止。

#include <stdio.h>
#include <stdlib.h>
#include "tokenizer.h"

int space_char(char c){
  if(c == '\t' || c == ' '){
    return 1;
  }
  return 0;
}

int non_space_char(char c){
  if(c != '\t' || c != ' '){
    return 1;
  }
  return 0;
}

char *word_start(char *str){
  int i = 0;
  while(space_char(str[i]) == 1){
    i++;
  }
  return &str[i];
}

char *word_terminator(char *word){
  word  = word_start(word);
  int i = 0;
  
  while(non_space_char(word[i]) == 1){
    i = i+1;
  }
  
  return &word[i];
}

int count_words(char *str){
  int count = 0;
  int i = 0;
  while(str[i] != '\0') {
      if(space_char(str[i]) && non_space_char(str[i + 1]))
    count++;
      i++;
    }
    count++;
  return count;
}

char  *copy_str(char *inStr, short len){
  int i = 0;
  //MALLOC FOR NEW STR :D
  char *outStr = malloc((len+1) *sizeof(char));

  while(i<=len){
    outStr[i]  = inStr[i];
    i= i+1;
  }
  return outStr;
}

char **tokenize(char *str){
  int i = 0;
  printf("%s","int i");
  int len;
  printf("%s","len");
  int all = count_words(str);
  printf("%s","all");
  char **tokens = malloc((all+1) * sizeof(char*));
  printf("%s","tokens");
  char *pointer = str;
  printf("%s","pointer");

  while(i < all+1){
    pointer = word_start(pointer);
    printf("%s","word_start");
    len = (word_terminator(pointer) - word_start(pointer));
    printf("%s","len");
    tokens[i] = copy_str(pointer, len);
    pointer = word_terminator(pointer);
    i = i + 1;
  }
  tokens[i] = 0;
  return tokens;
}

void print_tokens(char **tokens){
  int i = 0;
  while(tokens[i] !=  NULL){
    printf("%s\n", tokens[i]);
    i =  i + 1;
  }
}

void free_tokens(char **tokens){
  int i = 0;
  //can't pass  len as param  :D
  while(tokens[i] != 0){
    free(tokens[i]);
    i = i + 1;
  }
  free(tokens);
}

这是 tokenizer.c

#ifndef _TOKENIZER_
#define _TOKENIZER_


/* Return true (non-zero) if c is a whitespace characer
   ('\t' or ' ').  
   Zero terminators are not printable (therefore false) */
int space_char(char c);

/* Return true (non-zero) if c is a non-whitespace 
   character (not tab or space).  
   Zero terminators are not printable (therefore false) */ 
int non_space_char(char c);

/* Returns a pointer to the first character of the next 
   space-separated word in zero-terminated str.  Return a zero pointer if 
   str does not contain any words. */
char word_start(char *str); 

/* Returns a pointer terminator char following *word */
char *word_terminator(char *word);

/* Counts the number of words in the string argument. */
int count_words(char *str);

/* Returns a fresly allocated new zero-terminated string 
   containing <len> chars from <inStr> */
char *copy_str(char *inStr, short len);

/* Returns a freshly allocated zero-terminated vector of freshly allocated 
   space-separated tokens from zero-terminated str.
   For example, tokenize("hello world string") would result in:
     tokens[0] = "hello"
     tokens[1] = "world"
     tokens[2] = "string" 
     tokens[3] = 0
*/
char **tokenize(char* str);

/* Prints all tokens. */
void print_tokens(char **tokens);

/* Frees all tokens and the vector containing themx. */
void free_tokens(char **tokens);

#endif

这是 tokenizer.h,以防万一

【问题讨论】:

  • 使用调试器。它会立即告诉您触发 seg 错误的确切代码行。这是您应该做的最低限度的调试,并且应该在问题中发布。
  • -fsanitize=address (gcc & 我认为 clang) 非常适合调试这些问题。
  • 好吧,一方面,char word_start(char *str); 肯定不符合其评论描述。该函数应返回 char* 而不是 char
  • 关于:char *outStr = malloc((len+1) *sizeof(char)); 1) 表达式:sizeof(char) 在 C 标准中定义为 1。将任何内容乘以 1 没有任何效果,只会使代码混乱。建议删除该表达式。 2) 函数:malloc() 需要 size_t 参数,而不是 short 参数。 3) 函数:malloc() 可能会失败,因此应始终检查 (!=NULL) 返回值以确保操作成功。如果不成功(==NULL)则调用perror( "malloc failed" );清理并退出程序
  • 关于如下语句:printf("%s","word_start"); 这将位于stdout 流缓冲区中,直到执行:program exitsbuffer overflowan input operation。或 fflush() 被调用或 '\n' 被输出。 IE。这不会以“及时”的方式显示在终端上。建议:printf("%s\n","word_start");

标签: c memory segmentation-fault coredump


【解决方案1】:

好吧,我试着编译你的代码。

首先,在tokenizer.h 文件中,start_word() 函数被声明为返回一个字符,但在tokenizer.c 文件中,被定义为返回一个char *。根据tokenizer.h中的描述,改成返回一个char *

/* Returns a pointer to the first character of the next 
   space-separated word in zero-terminated str.  Return a zero pointer if 
   str does not contain any words. */
char *word_start(char *str);

现在,查看tokenizer.c 文件中的tonkenize() 函数,printf() 函数没有正确使用。要了解如何使用printf(),请查看this article

  1. 根据要打印的变量类型更改说明符。 "%s" 仅适用于字符串;
  2. 然后,添加'\n'(换行符)。只有在达到'\n' 后才会打印缓冲区中的字节;
  3. 最后,去掉变量名中的引号。在 C 中,引号始终表示字符串。

这里有一些例子:

int i = 0;
printf("%d\n", i);
int len;
printf("%d\n", len);
int all = count_words(str);
printf("%d\n", all);
// (...)

如果您不打算打印变量并且这些 printf() 调用仅用于测试,请删除第一个参数(但不要忘记 '\n' 字符)。

int i = 0;
printf("i\n");
int len;
printf("len\n");
int all = count_words(str);
printf("all\n");
// (...)

在这些printf() 调用之后,内存分配给malloc()

char **tokens = malloc((all+1) * sizeof(char*));

如果tokens变量代表一个以null结尾的字符串数组,变量all代表变量tokens拥有的字符串数量,这是正确的。问题是你没有检查内存分配是否成功。

char **tokens = malloc((all+1) * sizeof(char*));
if (tokens == NULL) {
    fprintf(stderr, "error: allocating memory\n");
    return NULL;
}

现在,关于 while 循环。

  1. 您首先获取单词的开头,然后计算长度,再次调用word_start(),但您已经知道单词的开头;
  2. 然后,复制字符串并移动到单词的末尾,再次调用word_terminator() 函数,而不是仅仅存储之前的结果。注意单词的结尾是下一次迭代的开始;
  3. i = i + 1;指令可以替换为i++;
  4. 迭代的范围必须是从零到字符串数减一。

这是我对tokenize() 函数的建议。

char **tokenize(char *str) {
    int i = 0;
    int all = count_words(str);
    char **tokens = malloc((all+1) * sizeof(char*));
    if (tokens == NULL) {
        fprintf(stderr, "error: allocating memory\n");
        return NULL;
    }
    char *start = str, *end = str;
    while (i < all) {
        start = word_start(end);
        end = word_terminator(start);
        tokens[i] = copy_str(start, end - start);
        i++;
    }
    tokens[i] = NULL;
    return tokens;
}

现在,关于copy_str() 函数。

  1. 你又忘了检查内存分配是否成功;
  2. while 循环的范围是从零到字符串长度减一;
  3. 您忘记在返回之前对字符串进行空终止。

这是我对copy_str() 函数的建议。

char *copy_str(char *inStr, short len) {
    int i = 0;
    char *outStr = malloc((len+1) *sizeof(char));
    if (outStr == NULL) {
        fprintf(stderr, "error: allocating memory\n");
        return NULL;
    }
    while (i < len) {
        outStr[i] = inStr[i];
        i++;
    }
    outStr[i] = '\0';
    return outStr;
}

查看word_start()word_terminator()的实现方式,我们可以清楚地了解到,如果我调用word_start(" ");word_terminator("asdfg");,就会发生分段错误。那是因为您只检查是否分别达到了非空格/空格字符。您需要检查'\0'(空字符)来打破字符串末尾的循环。

char *word_start(char *str) {
    int i = 0;
    while (space_char(str[i]) == 1) {
        if ( str[i] == '\0' )
            return NULL;
        i++;
    }
    return &str[i];
}

char *word_terminator(char *word) {
    word  = word_start(word);
    if ( word == NULL )
        return NULL;
    int i = 0;
    while (non_space_char(word[i]) == 1) {
        if ( word[i] == '\0' )
            return &word[i-1];
        i++;
    }
    return &word[i];
}

再次编译程序后,结果如下。

$ ./uimain
> Miguel Carvalho 22
Miguel Carvalho 22


> ^C
$

虽然程序可以运行,但代码可以改进。这里有一些注意事项。

  1. C 标准库包含一些对该程序有用的函数。搜索ctype.hstring.h
  2. count_words() 函数计数不正确。不要在循环中使用space_char()non_space_char() 函数,而是尝试使用word_start()word_terminator() 函数,直到返回NULL

【讨论】:

  • 很好的回应 :) 不要忘记可疑的“if(*input == '0'){}”行!我猜 OP 的意思是if(*input == 0)。可以简化为if(!(*input))
  • 感谢您的贡献,但我仍然收到相同的错误 :( 我什至将所有内容都更改为您发送的内容,但似乎没有任何效果。
  • @area 你确定你正确地改变了你的代码吗?您确定 while 循环在正确的范围内迭代吗?您确定在 while 循环之后没有忘记任何空终止符(NULL 用于字符串数组,'\0' 用于字符串)?再次验证。放一些printf() 调用(不要忘记'\n')来检测部分代码段错误发生。运行程序时不要插入额外的空格,因为对于每个额外的空格(单词之前、之后和之间),count_words() 函数计算一个单词。
  • @MiguelCarvalho 是的,当我使用调试器时,当 tokenize() 函数使用 copy_str() 时,我似乎收到分段错误(核心转储)错误,但我不知道为什么。我确定我正确地编写了 malloc 语句。实际上,我尝试完全按照您的建议编写它,但它抛出了错误。
  • @arae copy_str() 函数仅在 tokenize() 函数中调用。给定某个输入,例如"abc dfg hij",在tokenize() 函数segfault 中的while 循环的女巫迭代中捕获。如果它发生在第一次迭代中,请尝试了解作为参数传递的字符串是否实际上是"abc"。如果它发生在最后一次迭代之后("hij"之后),那是因为tokenize()函数的while循环中的变量all,女巫是count_words()函数的返回,与字数不匹配。 .
猜你喜欢
  • 2015-06-25
  • 1970-01-01
相关资源
最近更新 更多