C、在结构中使用动态数组时出现分段错误

问题描述

我正在尝试向 C 中的动态数组添加新元素(我知道我必须释放所有内存。我稍后会这样做),但我每次都会收到此错误

enter image description here

但是,奇怪的是,如果我像这样从终端编译,代码可以正常工作。

enter image description here

那么,错误在哪里,我该如何解决? 谢谢!

我所有的代码

main.c

    #include <stdio.h>
#include <stdlib.h>

typedef struct vector
{
    int size;
    int *array;
    int alreadyIn;
}vector;

vector *vectorInit(int size)
{
    vector *newVec = (vector *)malloc(sizeof(vector));
    if(!newVec){printf("No memory!\n"); return NULL;}
    newVec->size = size;
    newVec->array = (int *)malloc(size * sizeof(int));
    return newVec;
}

void allocNewMemory(vector *vect,int howMuch)
{
    vect->array = (int *)realloc(vect->array,(vect->size + howMuch) * sizeof(int));
    vect->size += howMuch;
}

void pushBack(vector *vect,int number)
{
    int howMuch = 5;
    if(vect && vect->alreadyIn < vect->size)
    {
        vect->array[vect->alreadyIn] = number;
        vect->alreadyIn++;
    }
    else
    {
        printf("Alloc new memory for %d elements...\n",howMuch);
        allocNewMemory(vect,howMuch);
        pushBack(vect,number);
    }
    
}

void printVector(vector *vect)
{
    for (int i = 0; i < vect->alreadyIn; i++)
    {
        printf("%d ",vect->array[i]);
    }
    printf("\n");
}

int main()
{
    int startSize = 4;
    vector * vec = vectorInit(startSize);

    for (int i = 0; i < 6; i++)
    {
        pushBack(vec,i+1);
    }
    

    printVector(vec);


    return 0;
}

解决方法

您从不初始化结构中的 alreadyIn 成员。这意味着它的值将不确定(并且看起来是垃圾或随机的)。

您需要将其显式初始化为零:

vector *vectorInit(int size)
{
    vector *newVec = malloc(sizeof(vector));
    if(!newVec)
    {
        printf("No memory!\n");
        return NULL;
    }
    newVec->size = size;
    newVec->array = malloc(size * sizeof(int));
    newVec->alreadyIn = 0;  // Remember to set this to zero
    return newVec;
}

这个问题应该很容易在调试器中检测到。


另请注意,我从 malloc 中删除了演员表。一个 should not cast the result of malloc,或者实际上任何返回 void * 的函数。