V613. Strange pointer arithmetic with 'malloc/new'.

The analyzer has detected a potential error in the code allocating memory. A pointer returned by the 'malloc' function or any other similar function is summed up with some number. It is very strange and it's highly probable that the code contains a misprint.

Consider this sample:

a = ((int *)(malloc(sizeof(int)*(3+5)))+2);

The expression contains many extraneous parentheses and the programmer must have got mixed up in them. Let's simplify this code to make it clearer:

a = (int *)malloc(sizeof(int)*8);
a += 2;

It's very strange to add number 2 to the pointer. Even if it should be so and the code is correct, it is very dangerous. For example, you might easily forget that memory should be free this way: "free(a - 2);".

This is the correct code:

a = (int *)malloc(sizeof(int)*(3+5+2));

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-761.


Bugs Found

Checked Projects
409
Collected Errors
14 072
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →
Accept