fork(2) download
  1. /* Write a function, char* strdup(const char*), that copies a C-style string into memory it
  2. allocates on the free store. Do not use any standard library functions. Do not use subscripting;
  3. use the dereference operator * instead. */
  4.  
  5.  
  6. #include <iostream>
  7.  
  8. char* strdup(const char* s) {
  9.  
  10. int size{0};
  11. for (;*s++; size++);
  12. char* str_ptr = new char[size + 1];
  13. char* str = {nullptr};
  14.  
  15. s -= size;
  16.  
  17. for (;*s++; *str_ptr++ = *s);
  18. str_ptr -= size;
  19.  
  20. str = str_ptr;
  21. delete[] str_ptr;
  22. return str;
  23. }
  24.  
  25. int main()
  26. {
  27. char* rdy = {strdup("HELLO")};
  28. std::cout << rdy << std::endl;
  29. }
Runtime error #stdin #stdout #stderr 0s 4500KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
free(): invalid pointer