I'm a beginner in C. I'm trying to implement a vector in C.
After successfully compiling the program with GCC. I get this error on the command line while I tried to run it.
I use GCC with wsl2 Linux ubuntu.<GCC (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0>
Here's part of my code.
Vector.h
#pragma once
typedef struct DynamicArray
{
int* data;
int size;
int capacity;
int is_resizeable; //resizeable = 0; unresizeable = 1;
} Vector;
void init_Vector
(Vector* self, int capacity, int is_resizeable, int default_value); //Initlizing a Vector
void finalize_Vector
(Vector** pp);
void fancy_print
(Vector* self);
I designed a constructor function that allows the user to destroy a vector in the program.
Here is a concrete implementation of the two functions.
Vector.c
void init_Vector
(Vector* self, int capacity, int is_resizeable, int default_value)
{
self->data = (int*)malloc(capacity * sizeof(int));
self->is_resizeable = is_resizeable;
self->capacity = capacity;
self->size = 0;
for (int i = 0; i < capacity; i++)
{
self->data[i] = default_value;
self->size++;
}
}
void finalize_Vector
(Vector** pp)
{
free(*pp);
*pp = NULL;
}
void fancy_print
(Vector* self)
{
printf("<CVector Object>: size: %d, capacity: %d, isresizeable: %d, {", self->size, self->capacity, self->is_resizeable);
for (int i = 0; i < self->size; i++)
{
printf("%d", self->data[i]);
if (i != self->size - 1)
printf(", ");
}
printf("}\n");
}
Then I wrote the main function to test my constructor and destructor functions.
main.c
int main(void)
{
Vector v;
init_Vector(&v, 5, 0, 1);
fancy_print(&v);
Vector* p = &v;
finalize_Vector(&p);
return 0;
}
GCC is compiled without any warnings or errors. But when I try to run my program, I got this.
<CVector Object>: size: 5, capacity: 5, isresizeable: 0, {1, 1, 1, 1, 1}
double free or corruption (out)
Aborted
I can't find out why there's a "double free or corruption", please help me.