【发布时间】:2017-08-18 02:55:30
【问题描述】:
所以,正如标题所示,我需要帮助我编写的一段代码,这会导致分段错误,代码如下:
vector* reads_file(char* name)
{
vector *vec = vector_new(); //creates a new vector with capacity = 0, size = 0 and elements = NULL
char *str_aux;
FILE *fp = fopen(name, "r");
if(fp == NULL){
printf("Error\n");
return NULL;
}
while(fgets(str_aux, BUFFER_SIZE, fp) != NULL){
if(vextor_inserts(vec, str_aux, -1) == -1)
return NULL;
free(str_aux);
}
fclose(fp);
return vec;
}
和:
int vector_inserts(vector* vec, const char* value, int pos)
{
int i, n;
if(vec == NULL || pos < -1 || pos > vec->size)
return -1;
/* increases vector's elements if there's not enough capacity */
if(vec->size == vec->capacity)
{
if(vec->capacity == 0)
vec->capacity = 1;
else
vec->capacity *= 2;
vec->elements = (v_element*)realloc(vec->elements, vec->capacity * sizeof(v_element));
if(vec->elements == NULL)
return -1;
}
/* if pos=-1 inserts in the end of the vector */
if(pos == -1)
pos = vec->size;
/* copies every element from the pos position till the end of the vector to pos+1 */
for(i=vec->size-1; i>=pos; i--)
{
vec->elements[i+1] = vec->elements[i];
}
/* allocates space for the new string on position pos */
vec->elements[pos].str = (char*)calloc(strlen(value)+1, sizeof(char));
if(vec->elements[pos].str == NULL)
return -1;
/* copies value */
strcpy(vec->elements[pos].str, value);
vec->size++;
return pos;
}
其结构是:
typedef struct
{
char *str;
} v_element;
typedef struct
{
/** total number of the vector's elements */
int size;
/** vector's capacity */
int capacity;
/** array of stored elements */
v_element* elements;
} vector;
哦和
#define BUFFER_SIZE 256
它编译得恰到好处(当使用另一段具有调用 reads_file(...) 函数的主函数的代码时)但是在执行它时,它在调用 vector_inserts(... ) 函数,但为什么会这样呢?我想不通。在我看来,没有指针被错误地调用。
任何帮助将不胜感激
【问题讨论】:
-
vector_new(); ?
-
fgets(str_aux, BUFFER_SIZE, fp):str_aux没有初始化。 -
怎么回事?或者,更好的是,为什么不呢?
-
你在调试器中看过了吗?由于您的问题中没有所有必要的代码,因此我们不能。
vextor_inserts看起来像一个错字,str_aux被释放但从未分配过。即使它是 malloced 并且您在 while 循环中释放了它,您也会在下一个循环中访问坏内存。 -
使用
fgets(str_aux, BUFFER_SIZE, fp),fgets()传递了 3 个值:fp是fopen(name, "r")的结果。BUFFER_SIZE是 256。当传递给fgets()时,str_aux中的值是多少?char *str_aux;声明了str_aux的存在,但是它有什么值呢?str_aux在代码中的哪个位置分配或初始化?
标签: c pointers struct segmentation-fault dynamic-memory-allocation