-3

I'm expecting for this code (second code) to run only 3 times. but it runs 6 on visual studio, and when I tried it on sololearn playground it run 4 times.

I've done other testing kind of like this code and the while loop never stops running. I thought that if the memory address did not hold any value it would be consider NULL, so it should return a 0, but it does not (for the first code).

well now I know why I'm wrong because is comparing the memory not the value inside the memory which makes sense why this code(first code) "never" stops.

///first code
int main() {
    int* s = malloc(5 * sizeof(int));
    int i = 0;
    while(i < 5){
        *(s + i) = i; 
        i++;
    }
    i = 0;
    while(s + i != NULL)
    {
        printf("hello");
        i++;
    }
    printf("%d", i);
    return 0;
}

, but then why does the second code stops if it is also comparing the memory address?

//second code
#include <stdio.h>
#include <stdlib.h>

int main() {
    int** s = malloc(3 * sizeof(int*));
    int x = 0;
    for(x = 0; x < 3; x++)
    {
        *(s + x) = malloc(1 * sizeof(int*));
    }


    int i = 0;
    while( *(s + i) != NULL)
    {   
        printf("hello");
        i++;
        
    }
    printf("%d", i);
    return 0;
}

And I guess the solution would be just to use a link list right?

Thomas
  • 1
  • 1
  • It's converting the `NULL` pointer to the integer `0`, so `0 == NULL` is true and the loop stops immediately. – Barmar Aug 16 '22 at 22:43
  • 1
    Not directly related: don't write `*(s + x)` but write `s[x]`, that's how it's done usually. – Jabberwocky Aug 16 '22 at 22:52
  • Nothing in your code ever sets anything to `NULL`. So why would you expect comparing things to `NULL` to indicate anything useful? – David Schwartz Aug 16 '22 at 23:08
  • In the `while` loop of your second code snippet, you are accessing the array `s` out of bounds, because you are not limiting the value of `i` to `0` to `2`. This invokes undefined behavior. – Andreas Wenzel Aug 16 '22 at 23:19

1 Answers1

1

In your while loop:

while(*(s + i) != NULL) { 

      printf("hello"); i++;
}

You check if the s[i]th element is NULL. This is a dangerous comparison and leads to undefined behaviour.

Since s can only store 3 int*, there is absolutely no guarantee there is a NULL somewhere in memory near s, so running the code will print an arbitrary number of "hello".

If you want to go through the array and check for NULL this is a better approach:

int i = 0; 

while(i < 3) 
{
    (s[i] != NULL) ? puts("hello") : puts("NULL found");
    i++;
}
programmer
  • 462
  • 1
  • 6