【问题标题】:Assertion failed after memcpy in c在 c 中进行 memcpy 后断言失败
【发布时间】:2015-01-21 02:55:14
【问题描述】:

我有一个为某个数组创建副本的函数。我的代码结构是:

typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

我写的函数是:

intarr_t* intarr_copy( const intarr_t* ia )
{
    unsigned int len;
    intarr_t* newia = malloc(sizeof(intarr_t));
    assert (newia);
    newia->data = malloc(sizeof(int)*len);
    newia->len = len;
    if (newia == 0)
    {
        return NULL;
    }
    else
    {
        memcpy (newia->data, ia->data, len*sizeof(int));
    }
    return 0;
}

当我测试函数时,它停止了我的函数并说我对 ia 的断言失败。我唯一拥有 ia 的地方是 memcpy。但我什至没有在我的函数中做断言。有人知道为什么它给了我一个断言错误吗?

【问题讨论】:

  • 原因可能是您从未将 len 变量初始化为一个值。很可能你真的想做unsigned int len = ia->len;之类的事情
  • len 未初始化。还要尽量保持你的代码连贯而不是混合。 NULL0 之类的,如果你真的是同样的意思。另一件事是您断言 newia 是否已正确分配,然后使用 if 语句检查它。我真的不知道这段代码应该做什么,因为你根据长度复制随机数量的数据......
  • unsigned int len = ia->len; 和 intXXX_t 是系统保留名称。

标签: c memcpy assertion


【解决方案1】:

您看到崩溃的原因是:

memcpy (newia->data, ia->data, len*sizeof(int));

在这一行中,len 的值是不确定的,因此您会看到崩溃。 我们还看到len 未初始化并在函数中的多个位置使用,这是不正确的,因为len 的值在没有初始化的情况下将是不确定的。

此外,您的代码中还有很多多余的东西。

在调用 malloc() 后检查内存分配成功或失败

intarr_t* newia = malloc(sizeof(intarr_t));

if(newia == NULL)
{
printf("Memory allocation failed\n");
return;
}

因此,这样做您不会访问无效内存。

接下来,您的命名约定太差了。你必须有可读的 typedef 不是像 intarr_t.

【讨论】:

  • @MattMcNabb 感谢您的关注,我更新了我的答案。
【解决方案2】:
// the following is assuming that 'len' is the number of ints in the memory 
// pointed to by 'data'
// I would strong suggest you use variable names that indicate
// if something is a pointer 
// (typically by pre-pending 'p' 
//  and capitalizing the first letter of the rest of the variable name)

intarr_t* intarr_copy( const intarr_t* ia )
{

    intarr_t* newia = malloc(sizeof(intarr_t));

    if( NULL == newia )
    { // then, malloc failed
        perror( "malloc failed for intarr_t" )'
        exit( EXIT_FAILURE );
    }

    // implied else, malloc for intarr_t successful

    newia->data = malloc(sizeof(int)*ia->len);

    if( NULL == newia->data )
    { // then malloc failed
        perror( "malloc failed for int array" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc of data array successful

    // set fields in newia
    newia->len = ia->len;
    memcpy (newia->data, ia->data, (sizeof(int)*ia->len));

    return( newia );
}

【讨论】:

    猜你喜欢
    • 2020-04-08
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    相关资源
    最近更新 更多