【问题标题】:program receive signal SIGSEGV segmentation fault程序接收信号 SIGSEGV 分段错误
【发布时间】:2016-01-03 18:52:13
【问题描述】:

我以 MCVE 为例,在我向 unpack_code 函数添加以下内容后(在它工作之前),程序崩溃并返回 255:

int ch_bit; 
unsigned int *ch_word; 
ch_bit = *p_ch_bit; 

到下面的代码

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

struct melp_param *par;

void unpack_code( unsigned int **p_ch_beg, int *p_ch_bit, 
        int *p_code, int numbits, int wsize,unsigned int erasemaks)
{
      int ret_code;
      int ch_bit;
      unsigned int *ch_word;
      ch_bit = *(p_ch_bit);
      *p_code = 0;

}

void melp_chn_read(struct melp_param *par, 
                   struct melp_param *prev_par)
{



}

int main(void)
{
      int bit_buffer[42];

    unpack_code(NULL, NULL, bit_buffer, 0, 0, 0);

    return 0;

}

一步步调试后:*p_ch_bit=Cannot access memory at address 0x0 和消息错误出现'segmentation error.....'

请帮帮我

【问题讨论】:

  • 在你的unpack函数中,这些变量没有被使用,你应该删除它们:ret_codech_bitch_word。变量ch_bit 被赋值但从未被访问过。
  • C++(和C)中的函数并不总是需要返回值。如果您总是从函数返回 0,请将函数的返回类型更改为 void 并删除 return 语句。
  • 尝试每行放置一个参数。这使您的代码更易于阅读(我必须保持水平滚动才能看到unpack 的所有参数)。
  • 另外,考虑将一些参数删除到unpack_code,因为它们没有被函数使用。
  • 这可能是一个X-Y 问题:需要回答的是关于更大的图片 的问题,而不是这些较低级别的问题。一种迹象是调用unpack_code,参数值全为0。

标签: c++ c pointers struct


【解决方案1】:

您正在为p_ch_bit 传递NULL,并且在尝试取消引用该指针时它会崩溃。

我建议您学习如何使用调试器来找出将来发生的崩溃问题。真的很有帮助!

【讨论】:

  • 这个 ch_bit = *(p_ch_bit);崩溃了,如果我评论它一切正常,我需要解决方案建议
  • 不要传入NULL?我不太确定你的程序想要做什么。
  • 并使用更好的名称...希望我永远不必维护您的代码,因为不知道它实际上做了什么。
【解决方案2】:
void unpack_code(unsigned int **p_ch_beg, int *p_ch_bit, int *p_code, int numbits, int wsize,unsigned int erasemaks)

     unpack_code(                   NULL,          NULL,  bit_buffer,           0,         0,                     0);

如果您将unpack_code 的定义排成一行并调用它,您会发现实际上您正在为p_ch_bit 参数传递NULL。你需要解决这个问题。

您可能需要执行以下操作:

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

struct melp_param *par;

void unpack_code( unsigned int **p_ch_beg, int *p_ch_bit, 
        int *p_code, int numbits, int wsize,unsigned int erasemaks)
{
      int ret_code;
      int ch_bit;
      unsigned int *ch_word;
      ch_bit = *(p_ch_bit);
      *p_code = 0;

}

void melp_chn_read(struct melp_param *par, 
                   struct melp_param *prev_par)
{



}

int main(void)
{
    int bit_buffer[42];
    int code; // <------------------------------------------- this

    unpack_code(NULL, bit_buffer, &code, 0, 0, 0); // <------ and this

    return 0;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多