V748. Memory for 'getline' function should be allocated only by 'malloc' or 'realloc' functions. Consider inspecting the first parameter of 'getline' function.


The analyzer detected an error that has to do with allocating memory for the getline() function without using the function malloc()/realloc(). The getline() function is written in such a way that if the already allocated memory is not enough, getline() will call realloc() to expand the memory block (ISO/IEC TR 24731-2). That's why memory can be allocated only using functions malloc() or realloc().

Consider the following example:

char* buf = new char[count];
getline(&buf, &count, stream);

In this code, memory for the function getline() is allocated using the new operator. If getline() needs more storage than that already allocated, it will call the realloc() function. The result of such call is unpredictable.

To fix the code, we need to rewrite it so that only functions malloc() or realloc() are used to allocate memory for the getline() function.

Correct code:

char* buf = (char*)malloc(count * sizeof(char));
getline(&buf, &count, stream);

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


Bugs Found

Checked Projects
336
Collected Errors
12 743