Loading...

Follow How Not To Code on Feedspot

Continue with Google
Continue with Facebook
or

Valid

Many beginners and students find C/C++ language hard to master because it requires them to think a lot. There are many language-specific quirks, especially in C++, that give students and programmers a hard time. It also has a steep learning curve and is rarely used in modern application development, which prompts many people to give up learning C/C++. However, even with these challenges, it is important for students to continue learning this programming language. This article highlights reasons why one should keep learning C/C++.

  1. It enables you to learn crucial programming ideas and understand other systems
  2. C and C++ helps you create more complex programs and understand crucial ideas. Other programming languages such as Python and Perly are useful for creating short scripts, but high-level programming will require knowledge of C/C++. These other languages may seem convenient because they provide you with everything and you do not need to learn or do much manually. However, this is not beneficial to a student or programmer because it is ideal that they learn how to create and do these bits.

  3. C/C++ is fast and efficient
  4. Higher level languages take more time to sort out because they are interpreted. C/C++ are faster and much more efficient. This should encourage you to keep learning these languages. Simplicity is another factor that provides efficiency in this particular case. C is simple and enables you to better grasp writing codes, compared to using high-level languages. This is possible because it has key words, raw pointers, and bitwise operators.

  5. There are many successful C/C++ projects
  6. Many big data engineers have used these languages to complete successful projects. C/C++ uses elements of other higher programming languages to make a combination that suits many projects. Developers are becoming creative while working with C/C++ to ensure that the projects are satisfactory. Some companies can provide you with engineers who will work only on your project or suggest recommendations on the project using C/C++, such as ActiveWizards.

  7. It influences and helps you learn other advanced programming languages
  8. C/C++ is a great influencer for other programming languages. These languages include Python, Numpy, and Java, which are built by C/C++. It explores the theories behind the languages, making you efficient in coding and programming. Learning C/C++ gives you the foundation to advance to other programming languages that are more complex. The simplicity of the language also creates a clear path for you to perform simple tasks.

  9. Many code samples are done in C/C++
  10. Many operating systems such as Linux, Windows, Android, and Mac are written in C/C++. Modern game engines and browsers like Firefox and Chrome are also written in C/C++. It has a long history with game development compared to other languages, which puts you ahead of the gaming community. The internal components of C also allow developers to have flexibility and total control over their projects.

Conclusion

It is evident that C/C++ can be associated with the powerful programming languages, and this is an indication that people should keep learning them. There are many more reasons and benefits of familiarizing yourself with C/C++, like complexity, total control, and creating a good image as a programmer, developer, or hacker.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
How Not To Code by Hownot2code - 3M ago

Incorrect string comparison

V547 Expression ‘m_resolvedName == L”en-US”‘ is always false. To compare strings you should use wcscmp() function. Calculator LocalizationSettings.h 180

wchar_t m_resolvedName[LOCALE_NAME_MAX_LENGTH];

Platform::String^ GetEnglishValueFromLocalizedDigits(....) const
{
  if (m_resolvedName == L"en-US")
  {
    return ref new Platform::String(localizedString.c_str());
  }
  ....
}

The example above shows incorrect comparison of strings. The programmer is in fact comparing pointers instead of string values by comparing the address of a character array with that of a string literal. These pointers are never equal, so the condition is always false, too. For correct comparison of strings, one should use the function wcscmp, for instance.

Please click here to see more bugs from this project.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
How Not To Code by Hownot2code - 3M ago

Little method can go a long way

V6007 Expression ‘(int)x < 0' is always false. BCrypt.java 429
V6025 Possibly index '(int) x' is out of bounds. BCrypt.java 431

private static byte char64(char x) {
  if ((int)x  index_64.length)
    return -1;
  return index_64[(int)x];
}

Issue N1. The expression ‘(int)x < 0’ is always false. The x variable cannot be negative, as it is of the char type. The char type is an unsigned integer. It cannot be called a real error, but, nonetheless, the check is redundant and can be removed.

Issue N2. Possible array index out of bounds, resulting in the ArrayIndexOutOfBoundsException exception. If the char64 method receives x with the value 128, the check won’t protect against ArrayIndexOutOfBoundsException. Maybe this never happens in reality. However, the check is written incorrectly, and one has to change “greater than” operator (>) with “greater than or equal to (“>=”).

Please click here to see more bugs from this project.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
How Not To Code by Hownot2code - 5M ago

An error in the condition

V560 A part of conditional expression is always true: (‘\n’ != c). params.c 136.

static int
EatWhitespace (FILE * InFile)
  /* ----------------------------------------------------------------------- **
   * Scan past whitespace (see ctype(3C)) and return the first non-whitespace
   * character, or newline, or EOF.
   *
   *  Input:  InFile  - Input source.
   *
   *  Output: The next non-whitespace character in the input stream.
   *
   *  Notes:  Because the config files use a line-oriented grammar, we
   *          explicitly exclude the newline character from the list of
   *          whitespace characters.
   *        - Note that both EOF (-1) and the nul character ('\0') are
   *          considered end-of-file markers.
   *
   * ----------------------------------------------------------------------- **
   */
{
    int c;

    for (c = getc (InFile); isspace (c) && ('\n' != c); c = getc (InFile))
        ;
    return (c);
}                               /* EatWhitespace */

The fault for all the confusion lies with the authors of the GNU Midnight Commander project, who made their own implementation of isspace in the file charset.h:

#ifdef isspace
#undef isspace
#endif
....
#define isspace(c) ((c)==' ' || (c) == '\t')

The custom macro, in its turn, treats only space and tab characters as whitespace characters. Let’s substitute that macro and see what happens.

for (c = getc (InFile);
     ((c)==' ' || (c) == '\t') && ('\n' != c);
     c = getc (InFile))

The (‘\n’ != c) subexpression is unnecessary (redundant) since it will always evaluate to true.

Please click here to see more bugs from this project.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
How Not To Code by Hownot2code - 6M ago

Check if the string contains itself

V3062 An object ‘attributeName’ is used as an argument to its own method. Consider checking the first actual argument of the ‘Contains’ method. AWSSDK.MobileAnalytics.Net45 CustomEvent.cs 261

/// 
/// Dictionary that stores attribute for this event only.
/// 
private Dictionary _attributes =
  new Dictionary();

/// 
/// Gets the attribute.
///    
/// Attribute name.
/// The attribute. Return null of attribute doesn't
///          exist.
public string GetAttribute(string attributeName)
{
  if(string.IsNullOrEmpty(attributeName))
  {
    throw new ArgumentNullException("attributeName");
  }
  string ret = null;
  lock(_lock)
  {
    if(attributeName.Contains(attributeName))
      ret = _attributes[attributeName];
  }
  return ret;
}

The analyzer has detected an error in the GetAttribute method: a string is checked whether it contains itself. From the description of the method it follows that if the attribute name (attributeName key) is found (in the dictionary _attributes), the attribute value should be returned, otherwise – null. In fact, as the condition attributeName.Contains(attributeName) is always true, an attempt is made to return the value by a key which might not be found in a dictionary. Then, instead of returning null, an exception KeyNotFoundException will be thrown.

Please click here to see more bugs from this project.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
How Not To Code by Hownot2code - 6M ago

Potential null dereference

V3080 Possible null dereference. Consider inspecting ‘traitFeatureWeightDistribution’. Recommender FeatureParameterDistribution.cs 65

public FeatureParameterDistribution(
         GaussianMatrix traitFeatureWeightDistribution, 
         GaussianArray biasFeatureWeightDistribution)
{
  Debug.Assert(
    (traitFeatureWeightDistribution == null && 
     biasFeatureWeightDistribution == null)
     ||
     traitFeatureWeightDistribution.All(
       w =>    w != null 
            && w.Count == biasFeatureWeightDistribution.Count),
    "The provided distributions should be valid 
     and consistent in the number of features.");
  ....
}

Let’s omit extra strings, having left only the logic of evaluating boolean value to make it easier to sort out:

(traitFeatureWeightDistribution == null && 
 biasFeatureWeightDistribution == null)
||
traitFeatureWeightDistribution.All(
  w =>   w != null 
      && w.Count == biasFeatureWeightDistribution.Count)

Again, the right operand of the operator || is evaluated only if the result of evaluating the left one is false. The left operand can take the false value, including when traitFeatureWeightDistribution == null and biasFeatureWeightDistribution != null. Then the right operand of the operator || will be evaluated, and calling traitFeatureWeightDistribution.All will lead to throwing of ArgumentNullException.

Please click here to see more bugs from this project.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
How Not To Code by Hownot2code - 6M ago

Unchecked input data

V1010 CWE-20 Unchecked tainted data is used in index: ‘strlen(command_buf)’.

static const char *basic_gets(int *cnt)
{
  ....
  int c = getchar();
  if (c < 0) {
    if (fgets(command_buf, sizeof(command_buf) - 1, stdin) 
          != command_buf) {
      break;
    }
    command_buf[strlen(command_buf)-1] = '\0'; /* remove endline */
    break;
  }
  ....
}

The analyzer warns about suspicious access to the command_buf array by an index. It is considered suspicious because unchecked external data is used as an index. Data is external as it was received through the fgets function from the stdin. Data is unchecked as there was no check before using. The expression fgets(command_buf, ….) != command_buf doesn’t count as in this case we check only the fact of receiving data, not its content.

The problem of this code is that under certain circumstances there will be a recording ‘\0’ outside the array, which will lead to the undefined behavior. For this, it is enough to just enter a zero-length string (a zero-length string in terms of the C language, i.e. the one in which the first character will be ‘\0’).

Let’s get a rough estimate of what will happen when feeding a zero-length string to the function:

  • fgets(command_buf, ….) -> command_buf;
  • fgets(….) != command_buf -> false (then-branch of the if statement is ignored);
  • strlen(command_buf) -> 0;
  • command_buf[strlen(command_buf) – 1] -> command_buf[-1].

Ooops!

What is interesting here is that this analyzer warning can be pretty “grasped between fingers”. In order to reproduce the problem, you need to:

  • get program execution to this function;
  • adjust the input so that the call of getchar() returned a negative value;
  • pass a string with a terminal null to the fgets function in the beginning and a function must successfully read the string.

Digging in sources for a while, I have formed a specific sequence of the problem reproducing:

  • Run fs_cli.exe in a batch-mode (fs_cli.exe -b). I’d like to note that to perform further steps, you need to make sure the connection to the fs_cli.exe server has been successful. For this purpose it is enough, for example, to locally run FreeSwitchConsole.exe as administrator.
  • After that we need to perform the input so that the call of getchar() returned a negative value.
  • Now let’s enter a string with a terminal null in the beginning (for example, ‘\0Oooops’).
  • ….
  • PROFIT!

You can find a video of reproducing the problem below:

FreeSWITCH - YouTube

Please click here to see more bugs from this project.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
How Not To Code by Hownot2code - 6M ago

A typo

V6001 [CWE-571] There are identical sub-expressions ‘!StringUtil.endsWithChar(name,'”‘)’ to the left and to the right of the ‘&&’ operator. JsonNamesValidator.java 27

public synchronized boolean isIdentifier(@NotNull String name,
                                         final Project project) {
  if (!StringUtil.startsWithChar(name,'\'') &&
      !StringUtil.startsWithChar(name,'\"')) {
    name = "\"" + name;
  }
  if (!StringUtil.endsWithChar(name,'"') &&
      !StringUtil.endsWithChar(name,'\"')) {
    name += "\"";
  }
 ....
}

This code fragment checks that the name is enclosed in either single or double quotation marks. If it’s not so, double quotation marks are added automatically.

Due to a typo, the end of the name is checked only for the presence of double quotation marks. As a result, the name in single quotation marks will be processed incorrectly.

The name

'Abcd'

due to adding extra double quotes will turn into:

'Abcd'"

Please click here to see more bugs from this project.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
How Not To Code by Hownot2code - 6M ago

Dangerous optimization (a vulnerability)

V597 The compiler could delete the ‘memset’ function call, which is used to flush ‘passwd_buf’ buffer. The memset_s() function should be used to erase the private data. challenge.c 366

/**
 * Crypt a given password using schema required for NTLMv1 authentication
 * @param passwd clear text domain password
 * @param challenge challenge data given by server
 * @param flags NTLM flags from server side
 * @param answer buffer where to store crypted password
 */
void
tds_answer_challenge(....)
{
#define MAX_PW_SZ 14
  ....
  if (ntlm_v == 1) {
    ....
    /* with security is best be pedantic */
    memset(hash, 0, sizeof(hash));
    memset(passwd_buf, 0, sizeof(passwd_buf));
    memset(ntlm2_challenge, 0, sizeof(ntlm2_challenge));
  } else {
    ....
  }
}

As you have already guessed, the title of this section is taken from the funny comment about security.

In brief, the compiler will delete the memset function because the buffers supposed to be cleared are no longer used. As a result, such data as hash or passwd_buf won’t be erased. This non-obvious feature of the compiler is discussed in more detail in the article “Safe Clearing of Private Data“.

Please click here to see more bugs from this project.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In the New year 2019, a PVS-Studio team decided to make a nice gift for all contributors of open-source projects hosted on GitHub or Bitbucket. They are given free usage of PVS-Studio static analyzer for development of open source projects.

We help to make code of open source software better and more reliable. Even though due to our publications more than 10000 errors have been fixed in open source projects, it is obviously not enough. Our team is physically not able to regularly check thousands of open source projects. That’s why in 2016 we offered a free version of PVS-Studio licensing. The only condition is having a special kind of comments in your code. The article “How to use PVS-Studio for Free” tells in more detail about this type of licensing.

In response to requests, we decided to make PVS-Studio usage possible for those who takes part in development of open source projects, posted on GitHub or Bitbucket. Authors of these projects don’t have to add any comments.

Everyone who wishes, can get a free license for 1 year. To get the license, you need to:

Upon expiration of the license, you can get a new license key in the same way.

The key is individual and can only be used to check open source projects published on GitHub/Bitbucket. Free license doesn’t extend to projects’ mirrors.

The old version of free analyzer usage with adding code comments remains in force. This mode has its own advantages. For example, students can use it to test their projects without having to upload them on GitHub/Bitbucket. Moreover, the previous version allows you to use the analyzer even for closed projects.

Conditions

Support for free users is carried out in replies on StackOverflow. The article “How to use PVS-Studio for Free” (see the section “Update: Support”) describes this condition in more detail. We’d like to note that StackOverflow isn’t s bug-tracker. Let’s discuss there questions, related to analyzer work and so on. To inform us of obvious bugs, as usually, please, write to our support.

The action of providing free licenses is timeless. However, if we feel that something has gone wrong, we reserve the right to change its terms or to stop it. We also reserve the right to withdraw a particular key without explanation.

As mentioned earlier, the ability to use free license does not apply to projects mirrors, such as Clang, Chromium, KDE and so on. Support of developers of such projects would require significant work from our team. So it would be quite fair if the company where these developers work got a paid license :).

Additional links:

Read Full Article

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview