t23837.nim 937 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. discard """
  2. output: '''
  3. Deallocating OwnedString
  4. HelloWorld
  5. '''
  6. matrix: "--cursorinference:on; --cursorinference:off"
  7. target: "c"
  8. """
  9. # bug #23837
  10. {.
  11. emit: [
  12. """
  13. #include <stdlib.h>
  14. #include <string.h>
  15. char *allocCString() {
  16. char *result = (char *) malloc(10 + 1);
  17. strcpy(result, "HelloWorld");
  18. return result;
  19. }
  20. """
  21. ]
  22. .}
  23. proc rawWrapper(): cstring {.importc: "allocCString", cdecl.}
  24. proc free(p: pointer) {.importc: "free", cdecl.}
  25. # -------------------------
  26. type OwnedString = distinct cstring
  27. proc `=destroy`(s: OwnedString) =
  28. free(cstring s)
  29. echo "Deallocating OwnedString"
  30. func `$`(s: OwnedString): string {.borrow.}
  31. proc leakyWrapper(): string =
  32. let ostring = rawWrapper().OwnedString
  33. $ostring
  34. # -------------------------
  35. proc main() =
  36. # destructor not called - definitely lost: 11 bytes in 1 blocks
  37. # doesn't leak with --cursorInference:off
  38. let s = leakyWrapper()
  39. echo s
  40. main()