Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find in my program a "const char* + int" expression

I'm in a source code migration and the converter program did not convert concatenation of embedded strings with integers. Now I have lots of code with this kind of expressions:

f("some text" + i);

Since C/C++ will interpret this as an array subscript, f will receive "some text", or "ome text", or "me text"...

My source language converts the concatenation of an string with an int as an string concatenation. Now I need to go line by line through the source code and change, by hand, the previous expression to:

f("some text" + std::to_string(i));

The conversion program managed to convert local "String" variables to "std::string", resulting in expressions:

std::string some_str = ...;
int i = ...;

f(some_str + i);

Those were easy to fix because with such expressions the C++ compiler outputs an error.

Is there any tool to find automatically such expressions on source code?

like image 216
vz0 Avatar asked Jul 12 '14 13:07

vz0


1 Answers

Easy! Just replace all the + with -&:

find . -name '*.cpp' -print0 | xargs -0 sed -i '' 's/+/-\&/g'


When trying to compile your project you will see, between other errors, something like this:

foo.cpp:9:16: error: 'const char *' and 'int *' are not pointers to compatible types
    return f(s -& i);
             ~ ^~~~

(I'm using clang, but other compilers should issue similar errors)


So you just have to filter the compiler output to keep only those errors:

clang++ foo.cpp 2>&1 | grep -F "error: 'const char *' and 'int *' are not pointers to compatible types"

And you get:

foo.cpp:9:16: error: 'const char *' and 'int *' are not pointers to compatible types
foo.cpp:18:10: error: 'const char *' and 'int *' are not pointers to compatible types
like image 150
esneider Avatar answered Sep 23 '22 10:09

esneider