Why must a pointer to a char array need strcpy to

2019-03-25 23:32发布

The first example does not work when you go to delete the pointer. The program either hangs when I add the null terminator or without it I get:

Debug Assertion Failed Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) from Visual Studio 2008

//Won't work when deleting pointer:
    char *at = new char [3];
    at = "tw"; //   <-- not sure what's going on here that strcpy does differently
    at[2] = '\0'; // <-- causes program to hang
    delete at;

//Works fine when deleting pointer:
    char *at = new char [3];
    strcpy(at,"t");
    at[1] = 'w';
    at[2] = '\0';
    delete at;

So what's going on when I use double quotes instead of strcpy? Both of them will cout the string perfectly and debugger does not show anything different.

9条回答
我命由我不由天
2楼-- · 2019-03-25 23:53

You mistake two things: making pointer point to something different (this is what assignment does) and copying some data to a place pointed by pointer.

at = "tw";

this code makes at point to a literal "tw" created somewhere in read-only memory. Trying to write to it is an undefined behaviour.

char *at = new char [3];
strcpy(at,"t");

this code allocates memory for three chars and makes at point to this part of memory (line 1) and then copies some data to memory pointed by at.

And remember, that memory allocated with new[] should be deallocated with delete[], not delete

I advice you to learn more about pointers. This discussion covers this.

查看更多
Root(大扎)
3楼-- · 2019-03-25 23:58

In the first example, you have caused a memory leak.

Your variable at is a pointer to a memory address, not the string itself. When you assign the address of "tw" to the pointer, you have lost the original address that you got with new. at now points to an address that you did not allocate with new, so you cannot delete it.

If you think of pointers as integers, it will probably make more sense. I've assigned arbitrary numbers as addresses for the sake of discussion.

char *at = new char[3];    // 0x1000
at = "tw";                 // 0x2000
at[2] = '\0';              // set char at 0x2002 to 0
delete at;                 // delete 0x2000 (whoops, didn't allocate that!)
查看更多
干净又极端
4楼-- · 2019-03-25 23:59

There are 3 things to understand:

1) char *at; is just a pointer variable.
A pointer variable simply means that it holds a memory address.

2) new char[3] returns the starting address of the memory allocated on the heap.

3) "hello" returns the address of the string literal.

char *at = new char [3];
//at now contains the address of the memory allocated on the heap


at = "hello";
//at now contains the address of the static string. 
// (and by the way you just created a 3 byte memory leak)


delete[] at; 
//WOOPS!!!! you can't do that because you aren't deleting 
// the original 3 chars anymore which were allocated on the heap!
//Since at contains the string literal's memory address you're 
// trying to delete the string literal.

A note about modifying read only memory:

Also you should never be modifying a string literal. I.e. this should never be done:

char *at = "hello";
at[2] = '\0'; 

The memory for string literals must be read only and if you change it, the results are undefined by the C++ language.

Since you're using C++:

Since you're using C++ please consider using the std::string type instead.

#include <string>

using namespace std;

int main(int argc, char **argv)
{
  string s = "hello";
  s += " world!";

  //s now contains "hello world!"

  s = "goodbye!";

  //Everything is still valid, and s contains "goodbye!"


  //No need to cleanup s. 

  return 0;
}
查看更多
等我变得足够好
5楼-- · 2019-03-25 23:59

Do not forget to use

delete []

whenever you are allocating something with [].

查看更多
乱世女痞
6楼-- · 2019-03-26 00:01

In the first example you are chaning the value at, in the second you are changing the value of what at points to. Assigning a char * to a double quoted string assigns it to a static const pointer.

In particular, in the first example at now points a different location in memory.

查看更多
男人必须洒脱
7楼-- · 2019-03-26 00:09

In your first example you are allocating some memory and pointing to it with the "at" variable. When you do

at = "tw"

you are effectively re-pointing the char * to a constant character string. This causes you to leak memory. When you go on to delete "at" you are attempting to delete stack memory.

strcpy goes through each character and copies their values to the new memory you allocate. This is also known as a deep copy.

查看更多
登录 后发表回答