by Dan East » Jul 24, 2001 @ 10:59am
There's nothing wrong with what you have, but that is not dynamic memory allocation. Anytime you have a string in your code (like "Hello" ) , that value is stored on the stack as a constant (which means it not not supposed to be modified). As Fredrick said, you're simply setting the pointer pString to point to the const string "Sample". You can have any number of pointers point to the same string. If the string is modified then it will appear that the string that all the pointers referred to was modified as well (because they are the same string). You have to explicitly set every single character to really copy a string. That is what the strcpy function does.<br><br>There's a huge difference between this and what you have:<br>[fixed]<br>char *pString=new char[10];<br>strcpy(pString, "Sample" ) ;<br>[/fixed]<br><br>Now that dynamically allocates a string 10 characters long, then fills it with the const string "Sample". Also, compilers can reuse the same const string value if it is found in multiple places in your code. For example:<br>[fixed]<br>char *pString1="Test string";<br>char *pString2="Test string";<br>[/fixed]<br>Since there are two identical const string values "Test string", the compiler may be smart enough to only create one const string and reuse it. Thus, depending on the type of compiler and build settings used, pString1 and pString2 may actually point to the same chunk of data. Thus if you were to modify one it will effect both. This may be true even across function bounderies. It is standard practice to never modify a const string, because there are many compiler and device specific issues that could be raised.<br><br>Now, this is also bad:<br>[fixed]<br>char *pString;<br>strcpy(pString, "Test" ) ;<br>[/fixed]<br>What does pString point to? That is unknown. So strcpy is filling bytes at an unknown location with "Test". Something like that will randomly crash, especially in release builds, because pString was not initialized and will "randomly" point to different chunks of memory.<br><br>Dan East<br><br>