Is there a problem with doing this?

Started by
7 comments, last by Aardvajk 17 years, 9 months ago
say you write the function: void textFunc(char text[]); and then you call the like this: textFunc("Hello World!"); Is that going to cause any problems with overwriting memory?
-----------------------------Download my real time 3D RPG.
Advertisement
(Assuming I remember my specs)
Eh, no. But certain uses of that string within textFunc will lead to badness.

Make the parameter const and there shouldn't be any problems, I think.
What exactly happens when you do that though? Is pointer space allocated for that function call and then destroyed after it is finished?
-----------------------------Download my real time 3D RPG.
No. If I remember correctly, Type VarName[] is a legal, but less common synonym for Type *VarName and behaves identically. (double check: yes, K&R use this syntax quite a bit for pre-allocated char arrays of arbitrary length)
array syntax for parameters to functions is 100% identical to pointer passing, unlike array syntax for variable declarations ... read this:

void textFunc(char text[]);

as:

void textFunc(char *text);
What part of the memory is the "hello world!" part located though?

My memory about this is a little rusty. Is the memory allocated for each function called a stack?
-----------------------------Download my real time 3D RPG.
Each function has its own local variables on the top of the stack.

In this case, the "Hello World" string is probably not given its own space each time you call the function.

Instead it is placed in some special read-only section of the executable and your program just passes a pointer to it. Try changing the first character and see if it crashes.
I think string literals are stored in some static type of storage. So when you pass a string literal to a function, it is passing a pointer to wherever the string is actually stored.

The documentation for the GCC says that string literals are stored in read-only storage. I think it does that so it can reuse the same memory if more than one string literal are the same. Other compilers might be different, I'm not sure.
The type of a string literal in C++ source is defined as const, so the compiler is free to and normally would store this in read-only data segment of your program.

So really, if you are passing it into a function your parameter should be (const char[]) rather than (char[]). My compilers would issue warnings if I omitted the const then passed in a literal string (I think).

This topic is closed to new replies.

Advertisement