Skip to content

Mishandling of sizeof on string literal in array size #2579

@ojwb

Description

@ojwb
$ cat test.i
%module x
%inline %{
unsigned char x[sizeof"hello world"];
unsigned char y[sizeof("hello world")];
%}
$ ../preinst-swig -python test.i
$ grep 'hello world[^"]' test_wrap.c 
      SWIG_exception_fail(SWIG_ArgError(res), "in variable '""x""' of type '""unsigned char [sizeof(hello world)]""'");
      for (; ii < (size_t)sizeof(hello world); ++ii) *(unsigned char *)&x[ii] = *((unsigned char *)inp + ii);
      SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""x""' of type '""unsigned char [sizeof(hello world)]""'");
      SWIG_exception_fail(SWIG_ArgError(res), "in variable '""y""' of type '""unsigned char [sizeof(hello world)]""'");
      for (; ii < (size_t)sizeof(hello world); ++ii) *(unsigned char *)&y[ii] = *((unsigned char *)inp + ii);
      SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""y""' of type '""unsigned char [sizeof(hello world)]""'");

Note SWIG loses the double quotes around the string literal inside the sizeof.

I spotted this while exploring additional tests for #2575 rather than in real world code, but while in this case sizeof(hello world) fails to compile, potentially the string without the quotes could be a valid thing to apply sizeof to though, so this bug could quietly produce incorrect code which compiles.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions