I usually program in C ++, but use some library functions for my char *. Some of the manpages, for example for getline, say that the input must be a malloced array.
Is it possible to use "new" instead?
I can see for my small sample that it works, but can it at some point lead to some strange undefined behavior?
I know that the "new" must match "delete" and "malloc" with "free."
I also do not use std :: string. And that is intentional.
thanks
, getline() MUST, .
, getline() realloc() , .
realloc(), free(), , malloc(). , malloc() :
: / malloc/?
" ", malloc "". " " ( , ) , " ", . .
man getline():
:
, getline(), * lineptr malloc() - * n . , getline() realloc(), * lineptr * n .
, , new, "malloced".
new
, getline ISO C. a getline ++, std::string. C fgets. ( , infile fgets, , , ):
getline
std::string
fgets
infile
// infile is some open FILE* object int mylen = 100; char* line = new char[mylen]; fgets(line, mylen, infile)
: std::string getline, ++.
"" malloc'ed .
( ):
These things will not make much difference in your program; as above, great for "new"
Your code will not fail unless a new or malloc fails, in which case 'new' throws an exception and malloc returns a NULL pointer.
EDIT: For this purpose, the array must be 'malloc'ed. Perhaps then I was wrong! Thanks, Martin! :)