I’m normally programming in c++, but are using some clibrary functions for my char*.
Some of the manpages like for ‘getline’, says that input should be a malloced array.
Is it ok, to use ‘new’ instead?
I can see for my small sample that it works, but could this at some point result in some strange undefined behavior?
I know that a ‘new’ should match a ‘delete’, and a ‘malloc’ with a ‘free’.
I’m also not using std::string. And this is intentional.
Thanks
The buffer passed to getline() MUST be malloced.
The reason is that getline() may call realloc() on the buffer if more space is required.
realloc() like free() should only be used with memory allocated by malloc(). This is because malloc() and new allocate memory from different storage areas:
See: What is the difference between new/delete and malloc/free?
Basically new uses “The “Free Store” while malloc uses “The Heap”. Both of these areas are part of the “application Heap” (Though the standard does not actually require an application heap as that is an implementation detail). Though they are both on the “Application Heap” these areas need not overlap. Whether they do is a detail of the implementation.
The man page for getline():
Notice this line: