Skip to content

"warning: ‘kind’ may be used uninitialized" in longobject.c #116592

@sobolevn

Description

@sobolevn

Bug report

New CI worker identified two possible problems: https://buildbot.python.org/all/#/builders/1379/builds/1

Objects/longobject.c: In function ‘long_format_binary’:
Objects/longobject.c:2321:13: warning: ‘kind’ may be used uninitialized [-Wmaybe-uninitialized]
 2321 |     else if (kind == PyUnicode_1BYTE_KIND) {
      |             ^
Objects/longobject.c:2197:9: note: ‘kind’ was declared here
 2197 |     int kind;
      |         ^~~~
Objects/longobject.c: In function ‘long_to_decimal_string_internal’:
Objects/longobject.c:2144:13: warning: ‘kind’ may be used uninitialized [-Wmaybe-uninitialized]
 2144 |     else if (kind == PyUnicode_1BYTE_KIND) {
      |             ^
Objects/longobject.c:1968:9: note: ‘kind’ was declared here
 1968 |     int kind;
      |         ^~~~

I don't think that this can ever happen, but, because of how code is written, static analysis is unsure about it:

cpython/Objects/longobject.c

Lines 2076 to 2097 in 1cc02ca

if (writer) {
if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
Py_DECREF(scratch);
return -1;
}
kind = writer->kind;
}
else if (bytes_writer) {
*bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
if (*bytes_str == NULL) {
Py_DECREF(scratch);
return -1;
}
}
else {
str = PyUnicode_New(strlen, '9');
if (str == NULL) {
Py_DECREF(scratch);
return -1;
}
kind = PyUnicode_KIND(str);
}

Notice how if (bytes_writer) does not have kind = part.

I think it is safe to assign kind as 0 by default. Because it is expected to be 1, 2, or 4.
And it is asserted to be in this range with ifs and assert (kind == PyUnicode_4BYTE_KIND);

One more thing: right now it is possible to pass both writer and bytes_writer or both NULLs.
I think that we should also an assert: only one of them can be present.

Linked PRs

Metadata

Metadata

Assignees

Labels

interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions