Is there a difference between malloced arrays and new arrays

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

+5
source share
3 answers

, getline() MUST, .

, getline() realloc() , .

realloc(), free(), , malloc(). , malloc() :

: / malloc/?

" ", malloc "". " " ( , ) , " ", . .

man getline():

:

, getline(), * lineptr malloc() - * n . , getline() realloc(), * lineptr * n .

+13

, , new, "malloced".

, getline ISO C. a getline ++, std::string. C fgets. ( , infile fgets, , , ):

// infile is some open FILE* object
int mylen = 100;
char* line = new char[mylen];
fgets(line, mylen, infile)

: std::string getline, ++.

+2

"" malloc'ed .

( ):

  • new/delete / malloc/free. /.
  • new , , malloc, typecasted (++)
  • new/delete realloc new/delete

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! :)

+1
source

All Articles