strarr.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2016 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef BLOATY_TESTS_STRARR_H_
  15. #define BLOATY_TESTS_STRARR_H_
  16. #include <memory>
  17. #include <string>
  18. #include <vector>
  19. // For constructing arrays of strings in the slightly peculiar format
  20. // required by execve().
  21. class StrArr {
  22. public:
  23. explicit StrArr(const std::vector<std::string>& strings)
  24. : size_(strings.size()), array_(new char*[size_ + 1]) {
  25. array_[size_] = NULL;
  26. for (size_t i = 0; i < strings.size(); i++) {
  27. // Can't use c_str() directly because array_ is not const char*.
  28. array_[i] = strdup(strings[i].c_str());
  29. }
  30. }
  31. ~StrArr() {
  32. // unique_ptr frees the array of pointers but not the pointed-to strings.
  33. for (int i = 0; i < size_; i++) {
  34. free(array_[i]);
  35. }
  36. }
  37. char **get() const { return array_.get(); }
  38. size_t size() const { return size_; }
  39. private:
  40. size_t size_;
  41. // Can't use vector<char*> because execve() takes ptr to non-const array.
  42. std::unique_ptr<char*[]> array_;
  43. };
  44. #endif // BLOATY_TESTS_STRARR_H_