Problem with Files (argv[]) as arguments for strncmp()

When I run the code (codes in attached image) nothing appears on the output screen when I try argv[] as arguments of strncmp() function. I searched on the web but I did not see any application like this for strncmp!

Everything I found was nearly like this:

int strncmp(
   const char *string1,
   const char *string2,
   size_t count
);

Not MSVC version code

I tried the codes in the image I attached in MSVC like this:


#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include<string.h>
void main(int argc, char *argv[]) {
    
    system("cls");
    if (!strncmp(argv[1], argv[2], 8))
        printf("Both strings are the same!");
    else
        printf("Not same!");
}

But nothing was on the output screen and no error and no warnings detected by MSVC. argv[1] and argv[2] each one is .txt files which I create before and their contents are exactly the same.

Then, I tried this code with two string arrays instead of previous .txt files, and it worked as I expected and fine. (According the strings the output was "Both strings are the same!" or "Not same!" )

How can I rewrite the codes in the image I attached, so that it works in MSVC as well?! How I pass my command line arguments It works on code::blocks

Upvotes: -1

Views: 106

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409422

What probably happens is that you haven't configured MSVC to pass the arguments correctly, which means you will pass a null pointer to strncmp (and possibly an indeterminate pointer as well).

That leads to undefined behavior, and very likely crashes.

To solve that you must always check argc to make sure that you have enough arguments.

The value of argc is the number of valid elements, so if you expect two arguments then you must check that it's at least 3:

if (argc < 3)
{
    printf("Not enough arguments! At least two expected.\n");
    return 1;
}

To be brutally honest, this should have been taught in any decent class, tutorial or book.

Upvotes: 0

Related Questions