#include<iostream>
#include<string.h>
int main()
{
 char* str="my name"; /*plz explain what is pointer-name,and what is string-
                              name here(realy confused) ? i am new to pointers :) */
 int len=strlen(str);
 char* ptr;
 ptr=new char[len+1]; /*is this ptr pointer or string*/
 strcpy(ptr,str);
 cout<<ptr;
 delete ptr;   /*how this works */
 cout<<endl<<ptr;    /*this 'ptr' should be destroyed as effect of "delete ptr"
                            ,but still displaying here when executed*/
 return 0;
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Well in "char* str="my name";" the _string_ "my name" is a list (or array) of characters (char) and "str" is a pointer to the first character in the list. So by incrementing the pointer "str" you get a pointer to the next character, then the next, and the next again, until you hit a character which is 0 (or '\0'), hence the name "null-terminated string". This is what "strlen(str)" does, it goes from character to character, starting from the pointer "str" to find the null character, and then it returns the count of how many characters there are before the null character (which terminates the string).

>>/*is this ptr pointer or string*/
Well as in the above, a pointer to chars (char*) is a pointer. If there is a null-character at the end, which it will after the call to "strcpy", it can be called a string, or null-terminated string.

>>/*this 'ptr' should be destroyed as effect of "delete ptr",but still displaying here when executed*/
Well, when you call "delete" it simply deallocates the memory pointed to by "ptr". This means that the program will consider that memory free to use for another memory allocation (like a call to "new"), but it doesn't replace the memory with anything, it simply marks it a free or available. When calling "delete", the pointer "ptr" is not changed in value, it still points to this address in memory, which still has the same null-terminated string saved there. That is why the line "cout<<endl<<ptr;" still outputs the original string. Obviously, this is not safe because since the memory is marked as available, if "ptr" is used after it was deleted, maybe, the program has already allocated that memory to another variable or array or string or anything and the memory might have changed and thus, no longer a valid string. So once you call "delete" on a pointer it is a good idea to set that pointer to NULL such that you don't risk using that memory again, without being allowed to.

I hope that was clear enough.

hi

from what i can see ill explain whats going on

#include<iostream>
#include<string.h>
int main()
{
   char* str="my name"; 
//char* means pointer so this creates a pointer to a character array called str.
//str is initilised upon creation to the string "my name". As far as i know this string
//is const and cannot be edited

   int len=strlen(str);
   char* ptr; //creates a second caracter pointer called ptr

   ptr=new char[len+1]; //new is a memory allocation keyword
   /*this creates a new array of characters (denoted by array brackets) char[len+1]
     had this been new char; then it would have pointed to a single character
     the memory is not assigned any value but the address of the first element is
     saved in the pointer ptr.
     
     this has the same effect as char ptr[len+1] with the difference that as the memory
     is dynamically allocated it can be deleted and a new size of array created .
   */

   strcpy(ptr,str); //strcpy (char* destination, char* source) copys the string "my name" to the character array pointed to by ptr

   cout<<ptr; 
   delete ptr; //this shouldent work it should be delete [] ptr. The [] tell the delete call its deleting an array not a single variable.
   cout<<endl<<ptr; /*this 'ptr' should be destroyed as effect of "delete ptr"
   ,but still displaying here when executed*/ //<-- the above fix should solve this i think
   return 0;
}

hope that helps any further explination (or if i have messed up which i hope i havent) just ask :)

edit: ooh ,... didnt see your post mike beat me to it,... well hopefully between the two posts you get the answer you need also what mike said is true about the delete call also and is a better answer than i gave for that. nice one mike :)

Edited 6 Years Ago by Kanoisa: n/a

@Kanoisa (saransh, please ignore):
>> //this shouldent work it should be delete [] ptr.
For primitive types like char, it works fine. When dealing with objects with non-trivial destructors, if delete[] is not called it will not call the individual destructor of each element, but the overall memory is still deleted fine (it's because the heap is made to deallocate memory blocks based only on the starting pointer and will deallocate the whole block whether delete or delete[] is called). Of course, it's a good habit to use delete[] everywhere, but not strictly required for POD types. So the behaviour of "cout<<endl<<ptr;" is expected to be like saransh reports it to be whether "delete" or "delete[]" is used.

@mike ,... Ahh i see that was never explained to me and i found out the hard way cleaning up an array of classes untill i used delete[] so i thought it was how it had to be done. thanks

@Kanoisa (saransh, please ignore):
>> //this shouldent work it should be delete [] ptr.
For primitive types like char, it works fine. When dealing with objects with non-trivial destructors, if delete[] is not called it will not call the individual destructor of each element, but the overall memory is still deleted fine (it's because the heap is made to deallocate memory blocks based only on the starting pointer and will deallocate the whole block whether delete or delete[] is called). Of course, it's a good habit to use delete[] everywhere, but not strictly required for POD types. So the behaviour of "cout<<endl<<ptr;" is expected to be like saransh reports it to be whether "delete" or "delete[]" is used.

That may work, and I can't speak for others, but I wouldn't consider it good form. You really should match a call to new[] (which the OP has, on what should be Line 9) with a call to delete[].

@OP:
I think the other responses have pretty well covered your questions. I don't think I need to add anything further...

Edited 6 Years Ago by Fbody: n/a

Thanks guy's i was just getting so confused up with this from last 5 hours...But now all of this fits exactly to my concepts .by the way i am following a book called "object oriented programming by-ROBERT LAFORE"(c++), is this all right naa (if you know)?

No, it's not okay. If the author manages to include six mistakes in such a short code example (assuming this is from the book and is not part of a "find the errors" exercise), then you need to get rid of the book ASAP.
If you don't want to spend money on yet another book, you might want to take a look at "Thinking in C++" by Bruce Eckel, which is freely available for download.

SORRY! to Kanoisa and Fbody..

I want to post this RETRACTION to my comment on delete being OK in this case. It is not! I was wrong and I am sorry for it. Please read this for details. I guess you learn new things everyday.. even after several years of programming...(it has also been a while since I used C-style arrays)

@Aranarth- but wht's the error in this ???

Edited 6 Years Ago by saransh60: n/a

but wht's the error in this ???

1. string.h is called cstring in C++
2. you can't cast a string literal (which is a constant char array) to a non-const char pointer.
3. you can't use cout and endl without their std:: qualifiers (there are three errors of these).
4. you must match every new[] with a delete[] (not delete).

Edited 6 Years Ago by Aranarth: n/a

#include<iostream>
#include<string.h>
int main()
{
char* str="my name"; /*plz explain what is pointer-name,and what is string-
name here(realy confused) ? i am new to pointers  */
int len=strlen(str);
char* ptr;
ptr=new char[len+1]; /*is this ptr pointer or string*/
strcpy(ptr,str);
cout<<ptr;
delete ptr; /*how this works */
cout<<endl<<ptr; /*this 'ptr' should be destroyed as effect of "delete ptr"
,but still displaying here when executed*/
return 0;
}

1. Line 2, For standard C++, the <string.h> header should not be used. It should be <cstring> instead.

2. There is no namespace resolution. You should be getting compile errors saying cout and endl are undeclared identifiers (not defined). To use them you must resolve the std namespace in any of 3 ways. This code doesn't use any of them.
A. Using statements, version 1:
using namespace std;

B. Using statements, version 2:
using std::cout; using std::endl;

C. Inline/Direct resolution:
std::cout << "Some output" << std::endl;

3. Line 8: The pointer is declared, but not initialized to NULL, To produce "safe" code, you must always either initialize pointers to NULL or allocate when declared.

4. Line 9: When the pointer is finally initialized/allocated it is not error-checked after allocation.

5. Line 10: You should never use strcpy(), it is not boundary safe and is asking for buffer overrun issues/errors. You should use strncpy() instead. strncpy() allows you to specify the size of the buffer, helping prevent buffer overrun errors.

6. Line 12: This has already been discussed. It should be delete[] instead.

3. Line 8: The pointer is declared, but not initialized to NULL, To produce "safe" code, you must always either initialize pointers to NULL or allocate when declared.

Nah, there's nothing unsafe about that (in this case) as long as you're not dereferencing ptr before initializing it.

4. Line 9: When the pointer is finally initialized/allocated it is not error-checked after allocation.

No need, new[] throws a std::bad_alloc exception on failure.

Nah, there's nothing unsafe about that (in this case) as long as you're not dereferencing ptr before initializing it.

That's exactly my point. In this particular case it is "fine", but what about in the future? What happens if you edit the code? Are those 2 lines going to remain consecutive? How long will the code not dereference ptr? Will the new code still wait until the appropriate time...? I won't guarantee it, will you?

No need, new[] throws a std::bad_alloc exception on failure.

I know that, but it is not caught, which results in a harsh abnormal program termination. Admittedly, this point really is 6-of-1 though. It'll terminate abnormally either way, but catching is less harsh.

Edited 6 Years Ago by Fbody: n/a

This article has been dead for over six months. Start a new discussion instead.