[LLVMdev] Strange behavior when converting arrays to strings

Martinez, Javier E javier.e.martinez at intel.com
Fri Jul 16 15:20:29 PDT 2010


Hello,

I found saw some strange behavior (to me) when converting constant arrays to strings. Consider the following example:
  std::string Text = "HelloWorld";
  unsigned TextLengthBefore = Text.length();
  ConstantArray *pArray = dyn_cast<ConstantArray>(llvm::ConstantArray::get(pModule->getContext(), Text, true));
  unsigned NumElements = pArray->getNumOperands();
  Text = pArray->getAsString();
  unsigned TextLengthAfter = Text.length();

After running this example here are the values in each variable:
  TextLengthBefore = 10
  NumElements = 11
  TextLengthAfter = 11

In the conversion from constant array to a string the null terminating character is added as part of the string and becomes the 11th character. This becomes a problem when the data is streamed out to a buffer because a NULL is inserted in the middle. Below is the code for getAsString:
1:  std::string ConstantArray::getAsString() const {
2:    assert(isString() && "Not a string!");
3:    std::string Result;
4:    Result.reserve(getNumOperands());
5:    for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6:      Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
7:    return Result;
8:  }

I think that the loop terminating condition in line 5 should be changed from != to <. Does this look right?

Thanks,
Javier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20100716/68b81a5f/attachment.html>


More information about the llvm-dev mailing list