【发布时间】:2014-02-22 02:43:34
【问题描述】:
我正在尝试生成一个将值“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 );
【问题讨论】:
-
在分配给
ia->data之前,您从未初始化ia。 -
您对
ia->data的分配也是错误的。你不能创建这样的数组,你必须调用malloc()然后设置每个元素。 -
有效
ia = realloc(<undefined value>, (<undefined value> + 1) * sizeof(intarr_t));。 -
你需要回到书本上,学习如何在 C 中使用数组和指针。
-
对不起,我忘了提到我在之前的任务中使用了 malloc to ia,我认为这与此有关……我更新了我的代码,使它看起来更接近我的目标提交到班级的服务器。
标签: c arrays segmentation-fault