0

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;
}
epic_rain
  • 1
  • 3
  • 1
    you have allocated single `int` and you can't write to unalloacted memory. and in `get_index` termination of `while-loop` is not correct. `get_index` can't give the current index use another variable to track it – TruthSeeker Apr 08 '22 at 16:23
  • 1
    You allocate space for a single `int` value. Which means the only valid index into your array is `0`. Your program go out of bounds, and will have *undefined behavior*. While you allocate memory dynamically, once allocated the size is fixed. – Some programmer dude Apr 08 '22 at 16:24
  • How come I don't get any errors other than in valgrind – epic_rain Apr 08 '22 at 16:32
  • 2
    [UB](https://stackoverflow.com/a/4105123/4139593) – TruthSeeker Apr 08 '22 at 16:39

0 Answers0