gpt4 book ai didi

c - C 中的段错误

转载 作者:行者123 更新时间:2023-11-30 21:30:58 25 4
gpt4 key购买 nike

我正在尝试生成一个代码,将值“val”附加到数组“ia”的末尾,但是我不断收到段错误。谁能帮我指出错误的根源可能来自哪里?

下面是我为任务 4 编写的测试代码。

intarr_result_t intarr_push( intarr_t* ia, int val )
{


if (ia ==0)
{
return INTARR_BADARRAY;
}

//making space for newarr
ia = realloc(ia, (ia->len + 1) * sizeof(intarr_t));

//copying data from ia and val to newarr
ia->data[ia->len - 1] = val;

//ia = newarr;
if (ia == 0)
{
return INTARR_BADALLOC;
}
else
{
return INTARR_OK;
}


}

使用以下自定义头文件:

/* Structure type that encapsulates our safe int array. */
typedef struct {
int* data;
unsigned int len;
} intarr_t;

/* A type for returning status codes */
typedef enum {
INTARR_OK,
INTARR_BADARRAY,
INTARR_BADINDEX,
INTARR_BADALLOC,
INTARR_NOTFOUND
} intarr_result_t;

/* TASK 4 */

// Append val to the end of ia (allocating space for it). If
// successful, return INTARR_OK, otherwise return
// INTARR_BADALLOC. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_push( intarr_t* ia, int val );

// If the array is not empty, remove the value with the highest index
// from the array, and, if i is non-null, set *i to the removed value,
// then return INTARR_OK. If the array is empty, leave *i unmodified
// and return INTARR_BADINDEX. If ia is null, return INTARR_BADARRAY.
intarr_result_t intarr_pop( intarr_t* ia, int* i );

最佳答案

问题是您realloc ia,而应该realloc ia->dataia本身的大小是恒定的,即sizeof(intarr_t)。正确的代码应该是:

ia->data = realloc(ia->data, (ia->len + 1) * sizeof(*ia->data));
/* ... */
if (ia->data == 0)
/* ... */
++ia->len;

关于c - C 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21948938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com