我要在 CS61C 给的框架里写一个 C 语言的变长数组。因为学艺不精碰到了奇怪的问题.和 malloc free 有关.
在 67-73 行删除之后新建出来的数组里,在应该是 0 的地方会有奇怪的数字,比如 5 和 6.
请神通广大的门友救一救
提供一点思路或者 debug 方法也可以.
核心代码如下:
struct vector_t {
size_t size;
int *data;
};
vector_t *vector_new() {
vector_t *retval;
retval = malloc(sizeof(vector_t));
if (retval==NULL) {
allocation_failed();
}
retval->size = 1;
retval->data = malloc(sizeof(int));
if (retval->data==NULL) {
free(retval);
allocation_failed();
}
retval->data[0]= 0;
return retval;
}
void vector_delete(vector_t *v) {
if(v!=NULL&&v->data!=NULL){
for(int i =0;i<v->size;i++){
v->data[i]=0;
}
free(v->data);
v->data=NULL;
v->size=0;
free(v);
}
}
void vector_set(vector_t *v, size_t loc, int value) {
if(loc>v->size){
int i =0;
int size = loc+1;
int *temp = malloc(size*sizeof(int));
v->size=size;
for(i=0;i<size;i++){
if(i<size-1)
{
temp[i]=v->data[i];
}
else{
temp[i]=0;
}
}
temp[loc]=value;
free(v->data);
v->data=temp;
}else{
v->data[loc]=value;
}
for (int i = 0; i < 20; i++)
{
printf("%d ",v->data[i]);
}
printf("\n");
}
int main(int argc, char **argv) {
vector_t *v;
printf("Calling vector_new()\n");
v = vector_new();
printf("Calling vector_delete()\n");
vector_delete(v);
printf("vector_new() again\n");
v = vector_new();
printf("These should all return 0 (vector_get()): ");
printf("%d ", vector_get(v, 0));
printf("%d ", vector_get(v, 1));
printf("%d\n", vector_get(v, 2));
printf("Doing a bunch of vector_set()s\n");
vector_set(v, 0, 98);
vector_set(v, 11, 15);
vector_set(v, 15, -23);
vector_set(v, 24, 65);
vector_set(v, 500, 3);
vector_set(v, 12, -123);
vector_set(v, 15, 21);
vector_set(v, 25, 43);
printf("These should be equal:\n");
printf("98 = %d\n", vector_get(v, 0));
printf("15 = %d\n", vector_get(v, 11));
printf("65 = %d\n", vector_get(v, 24));
printf("-123 = %d\n", vector_get(v, 12));
printf("21 = %d\n", vector_get(v, 15));
printf("43 = %d\n", vector_get(v, 25));
printf("0 = %d\n", vector_get(v, 23));
printf("0 = %d\n", vector_get(v, 1));
printf("0 = %d\n", vector_get(v, 501));
printf("3 = %d\n", vector_get(v, 500));
vector_delete(v);
printf("Test complete.\n");
return 0;
}