user5721565 user5721565 - 1 month ago 6
C Question

understanding memory leak in a C program

I am trying to scan integers from user after scanning the needed size.
I represent part of the code, which I figured out using valgrind (returning The error in valgrind is: "invalid write of size 4") that causes the memory leak. The memory leak is caused by the function below the main.
The problem occurs when the user enter size and afterwards enter more data than declared, for example SIZE = 8 and DATA = 1 2 3 4 5 6 7 8 9 10, I thought my code just ignores the extra data (and that was my intention), yet It all works well when I'm trying to debug it but crashes when it gets to the first free command.

I really don't understand why does it happen, can you help me out with it?

int main()
{
int size = 0;
int* user_numbers_array = (int*) malloc(size * sizeof(int));
int* second_array = (int*) malloc(size * sizeof(int));

printf("Enter size of input:\n");
scanf("%d", &size);

ScanNumbersFromUser(size, user_numbers_array)

free(user_numbers_array);
free(second_array);

return 0;
}

int ScanNumbersFromUser(int size, int* user_numbers_array)
{
int user_number = 0;
printf("Enter numbers:\n");
for(int i = 0; i < size; i++){
if(scanf("%d",&user_number) =! 1){ \\testing for valid input
printf("error");
return 0;
}
*(user_numbers_array + i) = user_number;
}
return 1;
}

Answer

You've malloced the arrays before you've gotten the user's size! Your arrays are of size 0.