我正在尝试生成一个代码,将值"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
,而应该重新分配ia->data
。 ia
本身的大小是恒定的,这是sizeof(intarr_t)
.正确的代码段应为:
ia->data = realloc(ia->data, (ia->len + 1) * sizeof(*ia->data));
/* ... */
if (ia->data == 0)
/* ... */
++ia->len;
你可以
试试这个
/* Structure type that encapsulates our safe int array. */
typedef struct {
int len;
int data[];
} intarr_t;
intarr_result_t intarr_push(intarr_t** ia, int val )
{
intarr_t *tmp = *ia;
if (tmp ==0)
{
return INTARR_BADARRAY;
}
tmp = realloc(tmp, sizeof(intarr_t) + sizeof(int) * (tmp->len + 1));
if (!tmp) return INTARR_BADALLOC;
/* copying data from ia and val to newarr */
tmp->data[tmp->len++] = val;
*ia = tmp;
return INTARR_OK;
}
int main(void)
{
intarr_result_t res;
intarr_t *arr = malloc(sizeof(intarr_t));
if (!arr) return 1;
res = intarr_push(&arr, 10);
/* TODO: Something with result */
res = intarr_push(&arr, 20);
/* .... */
return 0;
}