1

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;
}
senoron
  • 315
  • 1
  • 2
  • 11
  • You are not initializing your `alreadyIn` member. `malloc()` does not guarantee that all returned memory is initialized with zeros. It contains garbage. So `alreadyIn` is garbage. Hint: learn to use a debugger. You will make your life a lot easier. – Mike Nakis Jan 06 '21 at 21:38
  • Looks like you are already in the debugger. Learn to use it effectively. In this case, dump the variables at the point of the error and look for values that are incorrect. – kaylum Jan 06 '21 at 21:39
  • @MikeNakis I catch this error in debager) – senoron Jan 06 '21 at 21:41

1 Answers1

2

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 *.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621