PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Is this bad code?

int main ()

{
     char *pString;
     pString = "Sample";
       return 0;
}

I was just wondering when trying to dymaically allocate space for strings is this method bad? It seems to me it just writes over all the memmory at the &pString.
actually it creates space in memory for "Sample" and then sets pString to point to it. So you don't change the memory at pString in that case. Instead you actually change the pString pointer. If you later did like this:

*(pString+1)='i';

then the string pStrinf points to would be "Simple", cause I was changing the memory at pString.

Does this make sence to you?
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.

There's a huge difference between this and what you have:
[fixed]
char *pString=new char[10];
strcpy(pString, "Sample" ) ;
[/fixed]

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:
[fixed]
char *pString1="Test string";
char *pString2="Test string";
[/fixed]
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.

Now, this is also bad:
[fixed]
char *pString;
strcpy(pString, "Test" ) ;
[/fixed]
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.

Dan East

Good points Dan.  There's more on string pooling optimizations in the compiler docs.  Look at the /Gf and /GF compiler options.

One thing to note, the following is not a constant:

char* pszName = "Hello";

You are free to change the the value of pszName and you are free to change what pszName points to.

Now this:

const char* pszName = "Hello";

Means that you can't change what pszName points to.  i.e. you can't change pszName[1] to 'u' to get "Hullo".

Now this:

char* const pszName = "Hello";

Means that the data is non-const but the pointer IS const.  This means that later in the program, you can't do something like this:

pszName = "Hillo";


Here's the rules (courtesy "Effective C++" by Scott Meyers):

char *p = "Hello"; // non-const data, non-const pointer

const char *p = "Hello"; // const data, non-const pointer

char * const p = "Hello"; // non-const data, const pointer

const char * const p = "Hello"; // const data, const pointer

The easy way to remember this is to draw a vertical line through the asterisk in any of the declarations above.  If 'const' appears to the left of the line, then what's pointed to is constant, if 'const' is to the right of the line the pointer itself is constant.  If it's on both sides of the line, then both the pointer and the data are constant.  Clear as mud?




I was gonna reply but Digby, Dan and Fredrik beat me too it...as always...and with good stuff.

Where were you guys when I was learning to code?
I think Robert is now a-Gast. :) Sorry Robert, I get occasional puns about my last name too.
If you think that is a confusing mess, wait until you need to work with pointers to functions. The definitions are not very intuitive.

Dan East
Where were you guys when I was learning to code?


In wonderful QBasic land...(but that all depends on how long you've been coding)
Thanks alot guys, that acually answerd alot of questions but i guess ive got another

int main ()
{
       //This works fine
     char *szWord = "Cat";
     szWord = "Cut";
     //This does not
     char szSecondWord[] = "Dog";
     szSecondWord[] = "Dug";
     
     return 0;
}

What is wrong with the second method?

The board replaced my d's with faces that should read dog, dug.
but code in the {code}{/code} tags or just turn off smilies
When you do:
char szSecondWord[] = "dog";
it will automatically do it as if you had written:
char szSecondWord[3] = "dog";

when you then later try to do:
szSecondWord[] = "dug";

it will get quite mad, because then you try to change the length of the variable. Just remove the [] and it should work
Ya, but dog and dug are the same length. So why doesnt that code work?
In the definition of an array you can specify an initial set of values to populate the array. In actuality that array should simply point to that chunk of data that you provided. In other words those values weren't copied into your array - your array occupies the stack memory where your default values were loaded when that function was called. Neither C nor C++ provides a built in mechanism to copy an array. That makes sense because the size of an array is not always apparent at runtime. Further some arrays, such as a string, are terminated by a null character. That is why you must use string functions such as strcpy to copy data into a string (or do it manually).
A correction to Fredrik's sample:
[fixed]char szSecondWord[3] = "dog";[/fixed]
Would read:
[fixed]char szSecondWord[4] = "dog";[/fixed]
Because of the null terminator. The compiler would error on that one "array bounds overflow".

Dan East
First,

   char szFoo[] = "dog";

and...

   char szFoo[3] = "dog";

are not the same thing.  The first array is 4 chars in size and initialized as if you had done this:
   char szFoo[4] = {'d', 'o', 'g', '\0'};

The second array declaration will cause a compiler error because the array isn't big enough to contain the 4 chars.

Now, on to the other issue.  When you do this:

char szFoo[] = "dog";
   szFoo = "cat";

You're asking the compiler to convert szFoo to be a pointer to a char.

In the ANSI/ISO C++ spec, arrays cannot be converted to an l-value expression.  That means it can't be on the left hand side of the assignment operator ( = ).  This is covered in Clause 4 "Standard Conversion", paragraph 3.

They can be converted to an r-value expression though.  That's why you can do things like this:

   char *p = szFoo;

Here, szFoo is being converted to a char * on the right hand side of the assigment and that's OK by the spec.

Oh, and empty array brackets are only allowed when initializing an array at declaration time.

Hope that clears things up.

Ok, well check this out then is it bad code to lets say make a pointer

char* cChar = "Some Text";

then increment the pointer

cChar++

then deincrement

cChar--

Becuase once it points to the next address, wich contains o, it frees the memomry that was used to hold the S of Some, doesn't it? And if thats true it means that the S could get overwritten and when you deincrement it, it may point to  (garbage)ome Text instead of Somr Text.
Incrementing the pointer doesn't free the memory.  

The pointer is analogous to a telescope that lets you look at the contents of memory.  The contents of the memory are still there, you're just looking at a different part of it.  Does that make sense?

Okay, I think don't think you have a good grasp of pointers. Let's look at a contrived chunk of memory:
[fixed]0x1000 'M' 'y' ' ' 'T' 'e' 'x' 't' '/0'[/fixed]

In this case we are using a byte to store a letter (which is ANSI / ASCII). So if we look at the byte at memory address 0x1000 we will see it has a value of 77 (remember that all a byte is is a number from 0 to 255). 77 is the ASCII value for M. If we look at the byte at memory location 0x1001 we get 121, which is y. Now in your example you have a pointer to a character, so in our example it would point to the 'M' character:
[fixed]char *pTest="My Text";[/fixed]
Now all pTest is is a number that refers to a memory location. So in this example pTest has a value of 0x1000, which is the address of the first byte of the string. If we want to see what the actual value is at memory location 0x1000 then we use the indirection operator like so:
[fixed]if (*pText=='M') WhatDanSaysIsTrue=TRUE;[/fixed]
And...
[fixed]if ((int)pText==0x1000) WhatDanSaysIsTrue=TRUE;[/fixed]
In the above line I am treating pText like the number it really is, and checking to see if it is pointing to the memory address 0x1000. Now if I perform any math to pText, I only affect the number that the pText pointer is:
[fixed]pText+=3;[/fixed]
So pText was 0x1000, I incremented it by 3, and since a char is 1 byte, pText's numerical value is incremented by 3*1. So pText is 0x1003. If we look at our memory block above, we see that:
[fixed]*pText=='T';[/fixed]
What we did has nothing to do with changing the memory that contains the string. We just changed the value of a pointer that happens to point to that memory block.

Also, neither C nor C++ perform any type of memory management for you. If you don't delete or free it, then it is still there. Other languages like Java try to keep track of what data still has references to it and free what is not used. Don't confuse that with variable scope, which is where you declare a variable in a particular code block or function, and try to use it after it goes out of scope. In that case the data will have been reused by some other variable that is now in scope, and bad things may happen. Here is an example:
[fixed]char *MyFunction() {
  char szText[10]="Testing";
  return szText;
}[/fixed]
That function returns a pointer to the string szText. Well szText will be out of scope outside that function, so the data will not be valid. In that case you would either allocate the data with new or malloc and return that, or you could declare szText as static, which makes sure it hangs around, or you could create a global variable, which will be around as long as the program is running.

Dan East
Thanks, now that ive read the whole thread 10 or 12 times im pretty sure im getting the hang of it. What was throwing me all of was the concept of char* pszStuff = "blah" becuase i couldnt figure out how it was getting stored since i wasnt making the pointer acually point to a variable. But now i think the compiler allocates the space for "blah" on the stack then set the pointer equal to the address of where it stored "blah" then after the pszStuff goes out of scope is when the memmory where "blah" was stored is freed back to the system. Is this right?