senoron
senoron

Reputation: 344

C, Segmentation fault while using dynamic array in struct

I'm trying to add new element to dynamic array in C (I know that I must free all memory. I will do it later), but I get this error every time:

enter image description here

But, what is strange, if I compile from terminal, like that, code works properly.

enter image description here

So, where is the error and how i can beat it? Thank you!

All my code:

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;
}

Upvotes: 1

Views: 199

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

You never initialize the alreadyIn member in the structure. That means its value will be indeterminate (and seemingly garbage or random).

You need to explicitly initialize it to zero:

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;
}

This problem should have been easy to detect in the debugger.


Also note that I removed the casts from malloc. One should not cast the result of malloc, or really any function returning void *.

Upvotes: 2

Related Questions