I am writing this piece of code which works without any errors but when I run it with valgrind
it throws errors that Conditional jump or move depends on uninitialized value
which is caused by the while
loop trying to access the third element in the array
My question is can I use the function get_index()
since it does not show any warnings or errors when compiling with gcc -g -Wall -pedantic main.c
and outputs the same index as the idx
which is declared globally
#include <stdio.h>
#include <stdlib.h>
#define L 3
int *ptr;
int idx=0; // index
int get_index()
{
int x=0;
while(ptr[x])
x++;
return x;
}
void add_elem()
{
printf("Enter your number :\n");
scanf("%d",&ptr[idx]);
idx++;
}
int main(void) {
ptr = (int*)malloc(sizeof(int));
add_elem();
add_elem();
printf("Current index : %d\n",get_index());
printf("Original index : %d\n",idx);
return 0;
}