Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. # gets but safer
  2.  
  3. This is like `gets`. It is a drop in for `gets`. It is smarter though.
  4.  
  5. `gets_safe`, which is aliased to `gets` for convenience, takes an optional length argument, but it also uses GCC and Clang's `__builtin_object_size` builtin to calculate the length.
  6.  
  7. The length will not always be calculated properly, but for static arrays and `malloc`'d pointers in the current block with a fixed size (only with optimizations), it will usually pick up on it.
  8.  
  9. This also has a safety feature: If it can properly calculate the length and the supplied length is larger than the one it calculated, it will be an error. Additionally, when both the optional length parameter are omitted and the length cannot be calculated at compile time, it is an error.
  10.  
  11. Don't call this on a function with side effects, the arguments are used multiple times.
  12.  
  13. ```c
  14. 1) char *gets_safe(char *const buf, size_t len = sizeof(buf) /* basically */);
  15. 1) char *gets(char *const buf, size_t len = sizeof(buf) /* basically */);
  16. 3) void flush_line(FILE *f);
  17. 4) void flush_stdin()
  18. ```
  19.  
  20. 1) Reads a line from standard input.
  21. `buf`: A valid pointer to writable memory. If it is a static array or a pointer which has a size known by `__builtin_object_size`, `len` is not required. It is undefined behavior for `buf` to be a null pointer.
  22. `len`: An optional length for `buf`. When `__builtin_object_size` cannot be calculated, `len` is required. It is undefined behavior for `len` to be larger than the size of `buf`.
  23. **Returns**: `buf` on success, `NULL` on error.
  24. 2) A macro alias for 1)
  25. 3) Reads the remainder of a line from `f`. This is to be used after a partial `fgets` or a `scanf`.
  26. 4) Same as 3) but for stdin.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement