【问题标题】:Help needed in Segmentation Error in my C code我的 C 代码中的分段错误需要帮助
【发布时间】:2011-02-18 12:04:39
【问题描述】:

我一直试图确定我的程序在哪里生成分段,但无济于事。 我需要帮助来确定哪些字符串操作或字符指针在运行时导致了分段错误。程序编译成功,但运行时出现分段错误。

#include<curses.h>
#include<strings.h>
#include<unistd.h> 
#include<stdlib.h>

/*Implements a Scrolling headband that takes a string argument and continously scrolls*/               
int main(int argc, char* argv[])
{
    /*A Substring function to return substring of a string*/
    char *substr(const char *src, int start, int len);
    /*Appends a character to the Given string*/
    void append(char* s, char c);
    /***Check if the argument is invalid***/
    if(argc!=2)
    {
        puts("Invalid number of arguments: Usage:headband <String>");
    }
    /**Get headtext from the string argument argv[1]**/
    char *headtext = argv[1];

    /*headband(headtext);*/
    /*temporary variable to store strings as execution progresses*/
    char temp[100];
    /*Counter for streaming and scolling headband text*/
    int count = 0;
    /*Placeholder for temporary headband text*/
    char hold[100];
    int i;
    /*maximum x and y co-ordinates of the Screen*/
    int max_x,max_y;
    /*Initialize screen for ncurses*/
    initscr();
    /*Don't show cursor*/
    curs_set(0);
    /*Get terminal console dimensions*/
    getmaxyx(stdscr, max_y, max_x);
    /*Get console width set to default console screen width=80*/
    int consolewidth = max_x;
    /*Clear the screen*/
    clear();
    /*Set the first value as end of String for the momment*/
    temp[0] = '\0';
    /*Run this loop continuously to keep scrolling*/
    for (;;)
    {
        for(i=0; i < strlen(headtext); i++)
        {
            count++;
            /*Append headband text character by character to string hold*/
            append(temp, headtext[i]);
            move(0,consolewidth - count);
            if (consolewidth - count > 0)
            {
                mvaddstr(0,console_width-count,temp);
                refresh();
            }
            else if (consolewidth - count == 0)
            {
                strcpy(hold, temp);
                char q;
                int com = i;
                for(;;)
                {
                    /*Scroll text by triming one character at a time*/ 
                    /*from the left, then adding that character to the*/
                    /*right side of the text*/
                    com = com + 1;
                    if (com < strlen(headtext))
                    {
                        q = headtext[com];
                    }
                    else
                    {
                        com = 0;
                        q = headtext[com];
                        //q = hold[0];
                    }
                    strcpy(hold, substr(hold, 1, strlen(hold) - 1));
                    append(hold, q);
                    move(0,0);
                    clear();
                    mvaddstr(0,0,hold);
                    refresh();
                    usleep(50);
                }
            }
            usleep(50);
        }
    }
    return 0;
}

/*A Substring function to return substring of a string*/
char * substr(const char *src, int start, int len) 
{   
    char *dest = malloc(len+1);   
    if (dest) 
    {
        memcpy(dest, src+start, len);     
        dest[len] = '\0';   
    }   
    return dest;
}

/*Appends a character to the Given string*/
void append(char s[], char c)
{
    int len = strlen(s);
    s[len] = c;
    s[len+1] = '\0';
}

【问题讨论】:

  • 假设您在 Linux 环境中,您必须使用 GDB 对其进行调试。它将停在发生崩溃的确切行,因此您可以检查变量值以及几乎任何您想要的东西。
  • 可能不是问题,但您还没有终止第一条评论。如果这让编译器感到困惑,那么任何事情都可能发生。
  • @Dave - 由于 OP 声明程序可以编译,我冒昧地纠正了这个问题。

标签: c string segmentation-fault ncurses


【解决方案1】:

我不知道您使用的是哪个编译器,但这里有一个如何使用 GCC 和 GDB 进行调试的快速指南:

$ gcc -g file.c -o myexec   # the -g flag enables debug info

$ gdb ./myexec

现在您处于 GDB 提示符下。如果您需要设置命令行参数,请使用:

set args <arg1> <arg2> ...

然后运行你的程序

run

一旦它崩溃,你可以做各种各样的事情。它还显示您的错误发生在程序中的哪个位置。您可能想要使用这些命令:

bt            # prints the backtrace / call stack
print <expr>  # print value of an expression

有几个cheat sheets on the web,因此您可以快速了解可用的命令类型。

【讨论】:

  • 感谢@nominolo,我调试了程序,发现问题出在 stdscr 然后我在默认的 Unix 终端控制台上进行了测试(即未最大化,在 Gnome 中打开),它运行良好,没有分段错误.但是,在最大化控制台时,程序从屏幕中间打印并向左滚动。几秒钟后,它产生了分段错误。我发现我使用 ncurses 库打印到的 stdscr 窗口有它自己的最大屏幕宽度,这不是控制台的,所以它不会在它的窗口之外打印。谢谢。
  • 有没有一种方法可以获得 Unix 控制台的屏幕尺寸、将字符串/字符打印到屏幕上的特定位置或将光标移动到特定的屏幕位置而不使用 c 中的 ncurses 库.我已经搜索了这个,但无济于事。
  • 对不起,我从未使用过诅咒,所以我无法帮助您解决这个具体问题。有某些terminal escape codes 允许您移动光标,但您无法使用这些获得屏幕尺寸。我建议您为此打开一个单独的问题。
【解决方案2】:

使用手动调试方法;

#define DEBUG(A) fprintf(stderr, "%d step\n", (A))
#define PRINT(A) fprintf(stderr, "%s\n", (A))

#include<curses.h>
#include <strings.h>
#include<unistd.h> 
#include<stdlib.h>

int main(int argc, char* argv[]){

  char *substr(const char *src, int start, int len);
  PRINT("at top of the main" ) ; /***/
  DEBUG(1);
  void append(char* s, char c);

  if(argc!=2)
  {
    puts("Invalid number of arguments: Usage:headband <String>");
  }
  char *headtext = argv[1];
  DEBUG (2); 
  char temp[100];

  int count = 0;

  char hold[100];
  int i;

  int max_x,max_y;

  initscr();
  DEBUG (3);
  curs_set(0);

  getmaxyx(stdscr, max_y, max_x);
  DEBUG (4);
  int consolewidth = max_x;

  clear();
  DEBUG(5);
  temp[0] = '\0';

  for (;;)
  {
    for(i=0; i < strlen(headtext); i++)
    {
      count++;

      append(temp, headtext[i]);
      DEBUG(6);
      move(0,consolewidth - count);
      DEBUG(7);
      if (consolewidth - count > 0)
      {
        mvaddstr(0,console_width-count,temp);
        refresh();
      }
      else if (consolewidth - count == 0)
      {                
        char q;
        int com = i;
        strcpy(hold, temp);
        for(;;)
        {
          com = com + 1;
          if (com < strlen(headtext)){
            q = headtext[com];
            DEBUG (10);
          }else{
            com = 0;
            q = headtext[com];
            //q = hold[0];
          }
          strcpy(hold, substr(hold, 1, strlen(hold) - 1));
          append(hold, q);
          move(0,0);
          clear();
          mvaddstr(0,0,hold);
          refresh();
          usleep(50);
        }
      }
      usleep(50);
    }
  }
  return 0;
}

char * 
   substr(const char *src, int start, int len) 
{   
  char *dest = malloc(len+1);   
  PRINT ( "in substr" );
  if (dest) 
  {
    memcpy(dest, src+start, len);     
    dest[len] = '\0';   
  }   
  PRINT ("at the end of the sub);
  return dest;
}

void append(char s[], char c)
{       
  int len = strlen(s);
  PRINT( "in append function" );
  s[len] = c;
  s[len+1] = '\0';
  PRINT ( "at the end of the append function" );
}

编译它,然后你可以很容易地看到你在哪里出现分段错误

【讨论】:

  • 将宏中的 printf 替换为 fprintf(stderr, ...) 否则您可能看不到崩溃前的最后一条消息
  • 感谢@gcc,@Laurynas Biveinis,我进行了调试,发现分段错误来自DEBUG(7)。最大化的 Unix 控制台超出了 ncurses 库使用的“stdscr”窗口的控制台宽度。所以出现分割错误。当我在 Linux GNOME 中使用默认控制台窗口时,它不会产生分段错误。有没有一种方法可以获得 Unix 终端控制台的屏幕尺寸,将字符串/字符打印到屏幕上的特定位置或将光标移动到特定的屏幕位置而不使用 c 中的 ncurses 库。
【解决方案3】:

我看到的可能导致分段错误的最明显问题是在以下代码中:

if(argc!=2)
{
    puts("Invalid number of arguments: Usage:headband <String>");
}
char *headtext = argv[1];

确定提供了无效数量的参数后,您继续分配指向argv[1] 的指针。如果用户没有提供您的 参数,则结果是将NULL 传递给strlen()。这会导致未定义的行为,strlen(NULL) 通常会在 Linux\Unix 上崩溃。在我的简短测试中,提供 参数确实会导致头带滚动而没有任何崩溃。

您可以考虑将您的代码更改为类似于以下内容:

if(argc<2)
{
    puts("Invalid number of arguments: Usage:headband <String>");
    exit(EXIT_FAILURE);
}
char *headtext = argv[1];

更新
对于我认为的预期目的,您当前的代码似乎不必要地复杂(例如嵌套的无限循环)。当前形式的代码也有一些问题需要解决。有一个memory leak 源自在substr() 函数中对malloc() 的调用,随后丢失了指向已分配内存的指针。如果用户提供的文本大于temp[100] 缓冲区的大小,您将在append() 函数中溢出缓冲区。也不必多次计算headtext 的长度,因为它的长度不会改变。

我认为 curses 应该在 raw terminal escape codes 上使用。 curses 库实际上是原始终端代码的包装器,并提供灵活高效的 API,因此应用程序无需担心底层终端功能。也许NCURSES Programming HOWTOX/Open Curses, Reference Pages 可以派上用场。

我自己不是 curses 专家,但是,以下示例显示了另一种基于 curses 的方法,它松散地基于原始代码并且似乎具有相同的输出*

#include<curses.h>
#include<signal.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h> 

/* maximum x and y co-ordinates of the window */
int max_x, max_y;
/* pointer to headband buffer */
char * headband = NULL;
/* counter for streaming and scolling headband text */
unsigned int count;

/* Handler for window resize */
void handle_winch(int sig)
{
    /* Function for initializing curses & headband buffer */
    void my_init();

    /* Disable signal handler during reinitialization */
    signal(SIGWINCH, SIG_IGN);

    /* Reinitialize the window to update data structures */
    endwin();
    my_init();
}

/* Function for initializing curses & headband buffer */
void my_init()
{
    /* Initialize / Reinitialize screen for ncurses */
    initscr();
    curs_set(0);
    clear();
    refresh();
    getmaxyx(stdscr, max_y, max_x);

    /* Allocate / Reallocate and initialize scrolling headband buffer */
    free(headband);
    headband = (char *)malloc(max_x+1);
    memset(headband, ' ', max_x);
    headband[max_x] = '\0';
    count = 0;

    /* Setup signal handler for window resizing */
    signal(SIGWINCH, handle_winch);
}

/* Implements a scrolling headband that takes a 
 * string argument and scrolls continously */

int main(int argc, char* argv[])
{
    char * headtext;
    int headtext_len;
    int size;

    if(argc<2)
    {
        puts("Invalid number of arguments: Usage:headband <String>");
        exit(EXIT_FAILURE);
    }
    /* Get headtext from the argument argv[1] and compute length */
    headtext = argv[1];
    headtext_len = strlen(headtext);

    /* Call common initialization / reinitialization routine */
    my_init();

    /* Run this loop continuously to keep scrolling */
    for(;;)
    {
        /* Store & use copy of max_x in case original max_x is 
         * modified in signal handler by window resize event */
        size = max_x;

        /* Rotate headband by shifting entire buffer and then
         * appending next character from headtext buffer */
        memmove(&headband[0], &headband[1], size-1);
        headband[size-1] = headtext[count++ % headtext_len];

        /* Update window */
        move(0,0);
        mvaddstr(0,0,headband);
        refresh();
        usleep(50000);
    }

    /* Unreachable, but included for completeness */
    endwin();
    free(headband);
    exit(EXIT_SUCCESS);
}

* 包括窗口大小调整处理

【讨论】:

  • 谢谢,我已经更正了程序的这一部分,调试它,发现分段错误来自DEBUG(7)。最大化的 Unix 控制台超出了 ncurses 库使用的“stdscr”窗口的最大控制台宽度。所以出现分割错误。当我在 Linux GNOME 中使用默认控制台窗口时,它不会产生分段错误。有没有一种方法可以获得 Unix 终端控制台的屏幕尺寸,将字符串/字符打印到屏幕上的特定位置或将光标移动到特定的屏幕位置而不使用 c 中的 ncurses 库。
  • @realsaid - 虽然可以在没有 ncurses 的情况下做到这一点,但如果你学会使用 ncurses,而不是尝试使用原始转义序列。如何在没有 ncurses 的情况下做到这一点应该是另一个问题的主题。
  • @realsaid - getting terminal width in C 上的这个问题可能会有一些用处。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多