0

I'm confused with freeing or deleting pointer. For what I have read I have to use free with malloc , calloc , realloc and delete with new

But what if :

char * hello = "helloworld"; //need to use free()?
char * pointerWmalloc= (char*) malloc(sizeof(char)); 
pointerWmalloc="This need free for sure";
//here need to use free() am I right ? 
char * dupOfHello = strdup(hello); //need to use  free()? 
char * thisWnew= new Char(); // this need delete for sure 
char * charReturnedByFunc= returnchar(); // need to use free() for charReturnedByFunc??
user207421
  • 289,834
  • 37
  • 266
  • 440
Singh
  • 167
  • 10
  • 2
    You `free` what you `malloc` - and if a function returns a pointer its documentation has to clarify who's in charge of `free`ing it – UnholySheep Mar 21 '19 at 21:55
  • 2
    Preferably in C++ you should be sticking to `new`/`delete`. – Tzalumen Mar 21 '19 at 21:56
  • @UnholySheep malloc and strdup... – Breaking not so bad Mar 21 '19 at 22:02
  • 5
    @RingØ `strdup` falls into the second category I mentioned - its documentation states that the caller must `free` the pointer they receive from the function – UnholySheep Mar 21 '19 at 22:03
  • 1
    In C++ you should stick to, in order of preference, 1. Library containers and container-like classes such as `std::string` 2. Smart pointers 3. `new`/`delete` 4. `malloc` and friends and `free`. But before dynamically allocating anything, first ask yourself, "Would an Automatic variable do the job?" With references, move semantics, and return value optimization, you can do a lot with a dumb, old Automatic. More reading: [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) – user4581301 Mar 21 '19 at 22:11
  • I recommend familiarizing yourself with the concept of [String Literals](https://en.wikipedia.org/wiki/String_literal) – user4581301 Mar 21 '19 at 22:12
  • Thanks to everyone, learned more thanks to all of you than to my teacher – Singh Mar 21 '19 at 22:14
  • 1
    Also note `char * hello = "helloworld";` is not valid in C++. You need `const char * hello = "helloworld";`. – aschepler Mar 21 '19 at 22:18
  • @aschepler That's compiler/revision dependent. It's permitted in MSVC14/C++11 for sure, if still a terrible idea. Doesn't even give a warning. – Tzalumen Mar 21 '19 at 22:25
  • 2
    @Tzalumen Compilers do as they do, but in the C++ Standard that is verboten. – user4581301 Mar 21 '19 at 22:26
  • @user4581301 But which version of the standard forbids it? C++98? 03? 11? 14? 17? 20? There's no warnings given, so I'm going to have to assume it was forbidden in C++14 or later. – Tzalumen Mar 21 '19 at 22:30
  • My teacher never told us to use const char* , we always used char * = .... ; But thanks to everyone , now I will use const char*. Can I know why downvote ? If someone can explain me it would be great , so in future I can improve my question – Singh Mar 21 '19 at 22:30
  • 1
    The downvotes are mainly going to be because this information is fairly readily available from multiple locations both on and off SO. – Tzalumen Mar 21 '19 at 22:40
  • 1
    @Tzalumen Converting a string literal to non-constant pointer is deprecated in C++98 and C++03, and is forbidden in C++11 and later. Never trust MSVC to be correct. Though in this case you can get it to be correct using the "/Zc:strictStrings" switch. – aschepler Mar 21 '19 at 22:42
  • @Singh If that's really what your teacher told you he should be fired. *Why* did he tell you that? – user207421 Mar 21 '19 at 22:52
  • @user207421 he has always used char * = something;( maybe he's old school ?? Who knows) and no one has doubted whether it was Right until now – Singh Mar 21 '19 at 22:56
  • Maybe he's technically illiterate. The rules about `const char *` and string literal haven't changed. It's not like he has the choice. Does he like writing code that doesn't compile? Why don't you *ask* him why? You should never accept dogma from anybody in any profession. This is engineering, not magic. – user207421 Mar 22 '19 at 11:01
  • That said, the teacher is the gatekeeper to passing the class. Explain the problem privately and politely. – user4581301 Mar 22 '19 at 16:17
  • @user4581301 I asked him and he said : we use c++ minimally ( we mix c and c++ , and we use a lot c ) , so there is no difference for us if we use char or const char – Singh Mar 22 '19 at 17:23
  • Not at the compiler level, but at the runtime level... Let's just say C++ made `const char *` illegal in part because of the suffering of 30 years of C programmers (and ten years of pre-Standard C++ programmers) tripping over writes into read-only memory. If a programs spits out a bus error, odds are that was a missing `const`. [Recommended reading on why const is good](https://isocpp.org/wiki/faq/const-correctness). There is a strong case to be made for "Everything should be `const` until proven otherwise." – user4581301 Mar 22 '19 at 18:04

2 Answers2

2
char * hello = "helloworld"; //need to use free()?

"helloworld" is a const char* and hello is now a dynamic reference to it. (You will trigger a runtime exception if you try to change any characters in the string, or free this memory)

char * pointerWmalloc = (char*)malloc(sizeof(char));

This allocated memory needs to be free'd BEFORE reassignment to

pointerWmalloc = "This need free for sure";

which like hello now points to a const char* with the same restrictions.

char * dupOfHello = strdup(hello); //need to use  free()? 

this needs to be free'd

char * thisWnew = new Char(); // this need delete for sure 

This does need delete. Also, Char is not a class unless you make it one, but I think you meant char()

char * charReturnedByFunc = returnchar(); // need to use free() for charReturnedByFunc??

This one is tricky, it completely depends on what returnchar() returns a pointer to. A const char*? no. A char* owned by another object or function? Maybe. A char* allocated inside the function? Maybe. Unless you make it completely clear, you can't know if returnchar() returns a malloc'd or new'd char*.

All this and more is why it's recommended to avoid raw pointers in favor of std::unique_ptr and std::shared_ptr, avoid malloc in favor of new, and avoid char* in favor of std::string.

Tzalumen
  • 574
  • 2
  • 14
  • 2
    I'd reword that last one a bit. It doesn't matter what type is returned nearly as much as how what is returned was allocated. Some fool could even return a pointer to an Automatic. If the types don't line up, the compiler should catch it long before runtime (but as you noted in comments above not all compilers observe the type checked as tightly as they should). – user4581301 Mar 21 '19 at 22:31
  • 1
    Ownership also matters, since `returnchar()` could be returning a memory address to anyone's char* – Tzalumen Mar 21 '19 at 22:34
  • @user4581301If we're going to discuss dangerous decisions, there's also the ability to `const_cast` a `const char*` into a regular `char*` – Tzalumen Mar 21 '19 at 22:37
  • My point is the type doesn't matter. It's a side issue. The entire problem is you don't know how the memory was allocated and how it must be disposed of. The wording you have used distracts from this and seems to place an equal emphasis on an irrelevant issue. – user4581301 Mar 21 '19 at 23:37
1

I'll answer with comments in the code below:

char * hello = "helloworld"; // Do not free/delete pointer
                             // `hello` points to read-only memory
char * pointerWmalloc= (char*) malloc(sizeof(char)); // use free(pointerWmalloc) here
pointerWmalloc="This need free for sure"; // now you created a memory leak since pointerWmalloc now points to read-only memory. So do not free/delete

char * dupOfHello = strdup(hello); // use free(dupOfHello) here (as documented) 
char * thisWnew= new char(); // use delete thisWnew here
char * charReturnedByFunc= returnchar(); // need to read the documentation.
                // could be free, delete, none of the two or something else
Bo R
  • 1,899
  • 1
  • 5
  • 15
  • For read-only memory do u mean that I can't change the value of hello? Example : char * hello = "helloWorld"; hello = "thisIsNewHelloWorld";? Last more question , so for strdup I have always to use free? Also when a function returns strdup(orchard*)? Thanks – Singh Mar 21 '19 at 22:11
  • 2
    The answer will depend on the language you are using, C or C++. But in both cases you are allowed to re-assign a new value to `hello`. But shouldn't change the value of what `hello` is pointing to after `char*hello="helloworld";`. So avoid `hello[5]=W;`. But after `malloc` a simpel `*hello = 'x';` is ok, but now `hello` is no longer a pointer to an array of characters but *just* a char. – Bo R Mar 21 '19 at 22:20
  • @FrançoisAndrieux Actually, `char * hello = "helloworld";` is perfectly valid c++ as of at least MSVC 14/C++11, if extremely unwise. (I tested this whole mess) – Tzalumen Mar 21 '19 at 22:21
  • As @FrançoisAndrieux points out is correct with up-to-date version of the C++ language, but has been allowed previously in C++98. – Bo R Mar 21 '19 at 22:21
  • Thanks to everyone, got it ! – Singh Mar 21 '19 at 22:28