Unexpected behaviour in C code

If it doesn't fit anywhere else, drop it in here. (not to be used as a chat/nonsense section)

Moderator: Moderator Team

Post Reply
User avatar
Fraizeraust
Posts: 234
Joined: Thu Jan 05, 2017 11:46 am
Location: Italy
Contact:

Unexpected behaviour in C code

Post by Fraizeraust »

Hi everyone!

Recently I'm trying to enhance my C skills on my spare time. I wrote a code a few days ago and want to compile it today to get the results although it did not lead well that I expected. Here's the code I'm talking about:

Code: Select all

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

/* main() prototype function won't take any arguments, void. */
int main(void) {

  /* Variable declaration */
  char *StringSTDIN;
  char StringArgs[10];

  /* scanf() will scan for any typed character within stdin channel */
  printf("Would you like to close the program? (Yes/No)\n");
  scanf("%s", &StringSTDIN);

  /* If statement */
  if ( StringSTDIN == "Yes" || StringSTDIN == "yes" ) {
    printf("The program will exit...\n");
    exit (0);
    return (0);
  }
  else if ( StringSTDIN == "No" || StringSTDIN == "no" ) {
    printf("The program won't close, what would you like to do?\n");
    scanf("%s", StringArgs);
    printf("What you wrote...\n");
    printf("%s \n", StringArgs); // This should print from the stdout what the user wrote within the input
    return (0);
  }
}
As you can guess my intention in this code, if the user types "Yes" or "yes" the program will print a message and immediately exits the process. Otherwise it'll be given a chance to the user to type another thing (a character or just string) , scan the given input and output it to the screen. The compiler compiles the code without problems but if I write "Yes, No" the program exits immediately without printing any message declared in the code.

Maybe because I wrote the nested if body badly? What is it wrong? It'd be very appreciated if someone can help me with this. Thank you for reading!
a.k.a. GeoB99 -- ReactOS Kernel developer -- My Wiki page
User avatar
dizt3mp3r
Posts: 1874
Joined: Mon Jun 14, 2010 5:54 pm

Re: Unexpected behaviour in C code

Post by dizt3mp3r »

I'm not a c programmer but if I remember correctly, you need to pause the program closure at the end with another keyboard scan just before the final scan, hopefully you'll then see the output.

Amazing how similar these languages are, I am merely a javascript/PHP/VB6/DCL-er and my .js scripts would be more or less identical to simple C programs save a few differences.
Skillset: VMS,DOS,Windows Sysadmin from 1985, fault-tolerance, VaxCluster, Alpha,Sparc. DCL,QB,VBDOS- VB6,.NET, PHP,NODE.JS, Graphic Design, Project Manager, CMS, Quad Electronics. classic cars & m'bikes. Artist in water & oils. Historian.
erkinalp
Posts: 861
Joined: Sat Dec 20, 2008 5:55 pm
Location: Izmir, TR

Re: Unexpected behaviour in C code

Post by erkinalp »

Strings are not compared like that. You should use

Code: Select all

strcmp
-uses Ubuntu+GNOME 3 GNU/Linux
-likes Free (as in freedom) and Open Source Detergents
-favors open source of Windows 10 under GPL2
val
Posts: 69
Joined: Fri Feb 10, 2017 5:22 am

Re: Unexpected behaviour in C code

Post by val »

No offense, but you lack a basic understanding of C.
So you need to "enhance your skills" from the very beginning. Some book for beginners I guess would be helpful.
User avatar
dizt3mp3r
Posts: 1874
Joined: Mon Jun 14, 2010 5:54 pm

Re: Unexpected behaviour in C code

Post by dizt3mp3r »

That is exactly what he is doing Val. Trolling him is unnecessary here.
Skillset: VMS,DOS,Windows Sysadmin from 1985, fault-tolerance, VaxCluster, Alpha,Sparc. DCL,QB,VBDOS- VB6,.NET, PHP,NODE.JS, Graphic Design, Project Manager, CMS, Quad Electronics. classic cars & m'bikes. Artist in water & oils. Historian.
val
Posts: 69
Joined: Fri Feb 10, 2017 5:22 am

Re: Unexpected behaviour in C code

Post by val »

dizt3mp3r wrote:That is exactly what he is doing Val. Trolling him is unnecessary here.
I suggested him to read a book on C. where string manipulation is explained, and standard C I/O functions as well. and pointers. doing so would be a much straight way to learn the subject, than asking on a forum not even closely related to getting C basics.
if one writes:

Code: Select all

char *p;
...
if(p == "yes, I am comparing an unitialized pointer to char with a string literal"){
printf("trololo");
}
this means one needs to only start to learn C yet.
User avatar
Fraizeraust
Posts: 234
Joined: Thu Jan 05, 2017 11:46 am
Location: Italy
Contact:

Re: Unexpected behaviour in C code

Post by Fraizeraust »

I fixed it by myself with strcmp() function. Now it compares strings flawlessly. Thanks erkinalp!

@val: Well, you're kinda right and this is what I am doing. I just wanted someone to point out my mistake(s) in this code so I can be sure to not repeat it again.
a.k.a. GeoB99 -- ReactOS Kernel developer -- My Wiki page
User avatar
dizt3mp3r
Posts: 1874
Joined: Mon Jun 14, 2010 5:54 pm

Re: Unexpected behaviour in C code

Post by dizt3mp3r »

No-one should profess to be an expert in anything. Knowledge of a subject should just bring an understanding of exactly how little you actually know.
Skillset: VMS,DOS,Windows Sysadmin from 1985, fault-tolerance, VaxCluster, Alpha,Sparc. DCL,QB,VBDOS- VB6,.NET, PHP,NODE.JS, Graphic Design, Project Manager, CMS, Quad Electronics. classic cars & m'bikes. Artist in water & oils. Historian.
hbelusca
Developer
Posts: 1204
Joined: Sat Dec 26, 2009 10:36 pm
Location: Zagreb, Croatia

Re: Unexpected behaviour in C code

Post by hbelusca »

And of course...
... nobody saw the fundamental error in the code !!

My comments in the code use the "//" style comments.
Fraizeraust wrote:

Code: Select all

int main(void) {

  /* Variable declaration */
  char *StringSTDIN;     // Not initialized....
  char StringArgs[10];

  /* scanf() will scan for any typed character within stdin channel */
  printf("Would you like to close the program? (Yes/No)\n");
  scanf("%s", &StringSTDIN);   // Using uninitialized pointer ???

// I don't care about the remaining code....
  return 0;
}
StringSTDIN usage is buggy.

http://www.cplusplus.com/reference/cstdio/scanf/
User avatar
Fraizeraust
Posts: 234
Joined: Thu Jan 05, 2017 11:46 am
Location: Italy
Contact:

Re: Unexpected behaviour in C code

Post by Fraizeraust »

hbelusca wrote:StringSTDIN usage is buggy.
I took care of this variable as well. Thanks for pointing it anyways.
a.k.a. GeoB99 -- ReactOS Kernel developer -- My Wiki page
val
Posts: 69
Joined: Fri Feb 10, 2017 5:22 am

Re: Unexpected behaviour in C code

Post by val »

Fraizeraust wrote:I fixed it by myself with strcmp() function. Now it compares strings flawlessly. Thanks erkinalp!

@val: Well, you're kinda right and this is what I am doing. I just wanted someone to point out my mistake(s) in this code so I can be sure to not repeat it again.
i was not trolling, I adviced what I saw is the best for this level of knowledge. I've learnt C exactly that way.
pointers are a tricky topic, they should have been learnt about very thoroughly.
you messed with them a lot. that means you need something more educational than forum answers, cause noone's gonna write out several pages explanations on the topics as it's done in books.
scanf needs an address of a buffer where to store an input it scans for. that should be an address of an array of chars, and using scanf() already is a very bad pratice by the way, it's a direct way to stack buffer overflow errors - the most infamous source of the most severe vulnerabilities. using scanf() and gets() should be strongly discouraged even for educational purposes. honestly they should have been removed from the standard library at all. but, scanf() expects an address of a string buffer. this would be this one - char StringArgs[10]; in your code. In C, the name of an array variable without brackets, thus StringArgs, means an address of the array, exactly this you should pass to scanf(). this is the same as &StringArray[0] or even better - &*(StringArray + 0) :D. You instead passed to it the address of an unintitialized pointer StringSTDIN, which happenned to lay before in the stack. This results in stack corruption of course, because your pointer would get char codes instead of some address. your program exited gracefully just by the luck, - you didn't provide any actions for the third variant of the branch (where the code flow got inevitably, since you've messed up with string literals even more and they don't have a chance to evalute to true anywhere), and thus it exited, reaching the function's exit point.
String literals like this "my string" in C mean constant data, which compiler puts in a read only data section, and when you use such quoted strings in the code, think of it, that instead the pointer to this string in the data section would be inserted by the compiler. it's true, compiler inserts addresses there. So when you do such a comparison like this:
if(Pointer == "my string");
it's kind of valid from the compiler point of view, because you compare 2 pointers values possibly of the same type, but this expression never ever will evaluate to true, because you just won't know the address of the string "my string", you only could know it this way:
Pointer = "my String";
but then the comparison won't have any sense, it's always true.
of course you should do that:
strcmp(Buffer, "Yes");
where Buffer is your char Buffer[BUFFER_LENGTH]; where scanf() (hopefully) has put its input;
But this random explanation won't be helpful for you. Compared to books. That's why I adviced reading them.
ROCKNROLLKID
Posts: 307
Joined: Mon Oct 17, 2016 3:19 am
Contact:

Re: Unexpected behaviour in C code

Post by ROCKNROLLKID »

If I may say something, books are a great way to get started learning programming, but experience is the best learning mechanic. Books will teach you all the basics, but it's not going to teach you how to build a project the way you want it built. You have to learn that yourself. By attempting to actually create something, it probably shows maybe you have gone past the book learning phase and actually want to develop something. Every beginner is going to have issues, so don't feel too bad.
Post Reply

Who is online

Users browsing this forum: No registered users and 19 guests