Thread: safe gets (allocating)?

  1. #1
    Algorithm engineer
    Join Date
    Jun 2006
    Posts
    286

    safe gets (allocating)?

    Hi!

    I'm wondering whether there is a safe gets which allocates new memory for the string, like scanf("%as", &s), with the difference that it scans the whole line instead of stopping at a blank space. Or can you modify scanf("%as", &s) to stop reading only at new line characters?
    Come on, you can do it! b( ~_')

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    fgets() is the safe option of gets, but it's still not allocating memory - you have to give it a "large enough" buffer - it will stop at the end of input, and you can detect if it read the entire line or not.

    In linux there is "gnu readline" which returns a pointer to a string.

    You can of course write a readline compatible function for Windows (with the same or a different name), using for example fgets() in (with a large temporary buffer and allocating a second buffer and copy into the allocated memory) or using fgetc() and allocating the buffer as you need.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. thread safe in my code to manipulate List?
    By George2 in forum C# Programming
    Replies: 8
    Last Post: 05-01-2008, 06:57 AM
  2. Dynamically allocating 3D array
    By ssharish2005 in forum C Programming
    Replies: 8
    Last Post: 02-26-2008, 04:07 PM
  3. type safe issue
    By George2 in forum C++ Programming
    Replies: 4
    Last Post: 02-12-2008, 09:32 PM
  4. Bjarne's exception safe sample
    By George2 in forum C++ Programming
    Replies: 13
    Last Post: 12-28-2007, 05:38 PM
  5. How safe is it?
    By hermit in forum A Brief History of Cprogramming.com
    Replies: 40
    Last Post: 05-08-2002, 09:33 PM