-1

I was trying to golf a simple code that ask for a word and repeat it without the first letters until the word is empty
For exemple :

hello
ello
llo
lo
o

I've made a code that work great :

#include <stdlib.h>
#include <stdio.h>


int main(){
    char* p=(char*)(malloc(50*sizeof(char)));
    scanf("%s",p);
    while (*p!='\0',printf("%s\n",++p)>1);
}

But before, I first try a version with :while (*p!='\0',printf("%s\n",++p)); and when I try it, it was working great with the word inputed but then it started doing the same with my PATH. So I was wondering why the program always prompt my PATH ? I'm on Windows 7 64-bits with mingw.

Thanks all ! Have a good day !

A.Braut
  • 1
  • 2
  • Please post your code and don't describe it. And what `PATH` are you talking about?? You can [edit] your question. – Jabberwocky Nov 16 '18 at 15:00
  • `*p!='\0',printf("%s\n",++p)>1`...are you sure? – Sourav Ghosh Nov 16 '18 at 15:04
  • Why do you have the `printf` and `++p` inside the `while` condition? That's just very confusing and likely what's causing your problems. – Kevin Nov 16 '18 at 15:04
  • 3
    That while() loop only tests the return value of printf(), the *p!='\0' expression does nothing at all. Do get familiar with the way the comma operator works: https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do – Hans Passant Nov 16 '18 at 15:05
  • Could you elaborate how PATH is related to this? Also, the comma operator `,` evaluates all the expressions but its result is the value of the rightmost expression. Thus, `*p!='\0'` is useless here. – nm_tp Nov 16 '18 at 15:07
  • I think the path is random garbage in memory that happens to be after the memory contained in p. – Owl Nov 16 '18 at 16:57

1 Answers1

0

It's because of how the comma operator works.

It evaluates the left and right hand sides, and throws away the left-hand side result. That means the condition *p != '\0' is evaluated, but the result is not used.

Instead its the result of the printf function that will be used as the sole condition in the loop. It will return the numbers of characters printed, including things like space and newline. And since you print a newline, the returned value will always be at least 1. And in C only 0 is considered false, and would have stopped the loop.

You should be using the logical AND operator && instead of the comma operator:

while (*p!='\0' && printf("%s\n",++p));

Now when the left-hand side (i.e. *p!='\0') becomes false, then the loop should stop.


What happens without the above change, or the change you made, is that your loop will go out of bounds of the string and even your allocated memory. That leads to undefined behavior, which means just about anything could happen.

For you it seems that part of the environment happens to be next in memory to your allocated memory.

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