Pointer vs Table for strncpy

Hi

I'm using Visual C++ 2005. Why code below works:

1
2
3
	char text1[] = "aaaaaa";
	char text2[] = "bbbbb";
	printf("%s\n", strncpy(text1,text2,5));


while this doesn't (access violation)

1
2
3
	char *text1 = "aaaaaa";
	char *text2 = "bbbbb";
	printf("%s\n", strncpy(text1,text2,5));


I will be grateful for explanation.

W.
Because in the latter example, the compiler is putting the pointer text1 in the data segment but the string is being put in the (read-only) code segment.
In the former example (array), the entire array is put in the data segment.
The first declares an array of characters (which you will presumably want to manipulate), so it is placed in the writeable data storage section of your program. The character literal only tells the compiler how to initialize it.

The second declares a pointer to a static (meaning, immutable, or 'cannot be modified') string of characters which are stored in the read-only data storage section of your program. The character literal is placed verbatim in your program.

The trick is that literals are, by definition, immutable. Some older compilers may not enforce this, and your programs would compile and run equally well with them. However, these days that is non-standard.

If you are using a version of GCC prior to 4.x, you can tell it to assume that you might change the literal (so it is stored in the writeable data section also) using the -fwriteable-strings option:
1
2
3
4
5
6
7
#include <stdio.h>
#include <string.h>

int main() {
  printf( "%s\n", strcpy( "Stupider", "Stupid" ) );
  return 0;
  }

gcc -fwriteable-strings stupid.c


The latest versions (4.x series) of the GCC have finally removed that option and require your code literals to actually be constant.
http://gcc.gnu.org/gcc-4.0/changes.html

Hope this helps.

[edit] Hmm, too slow again. This time I have an excuse though... it took me a few minutes to figure out why my GCC wouldn't take -fwriteable-strings... :-P
Last edited on

Thanks for all replies. Now I understand.

W.
Topic archived. No new replies allowed.