Doubt in C pointer concept

vila8's Avatar
Newbie Member
Hi folks,

I have been stuck with a problem for hours .Kindly help me out of this predicament.

Consider the following code:


char *dest;
dest = (char*) malloc (10);
dest = "HiHello";
printf("\n the size of dest:%d", strlen(dest));
*dest='A';

The last line throws a segmentation fault while strlen of dest works.
But the follwoing code works perfectly:

char *dest;
dest = (char*) malloc (10);
strcpy(dest,"HiHello"); ---> Please note this change.
printf("\n the size of dest:%d", strlen(dest));
*dest='A';

The latter snippet works fine but the former doesnt.I dont understand why.Can anyone please explain to me why this hassle !!
0
tailhook123's Avatar, Join Date: May 2007
Go4Expert Member
Quote:
Originally Posted by vila8
Hi folks,

I have been stuck with a problem for hours .Kindly help me out of this predicament.

Consider the following code:


char *dest;
dest = (char*) malloc (10);
dest = "HiHello";
printf("\n the size of dest:%d", strlen(dest));
*dest='A';

The last line throws a segmentation fault while strlen of dest works.
But the follwoing code works perfectly:

char *dest;
dest = (char*) malloc (10);
strcpy(dest,"HiHello"); ---> Please note this change.
printf("\n the size of dest:%d", strlen(dest));
*dest='A';

The latter snippet works fine but the former doesnt.I dont understand why.Can anyone please explain to me why this hassle !!
Sure... a char * is a pointer to a string of characters terminated by a \0. Strcpy tacks the null terminator on the end.. your original code using the '=' notation doesn't. You need to force the character just after the o in hello to be a null 0. Once that happens strlen knows where to stop. Its possible you could just make it:

dest = "HiHello\0";
0
karri's Avatar, Join Date: Jun 2007
Light Poster
I think it is because as dest is a pointer initialised to point to a string constant if the contents of the string are modified the result is undefined. But in the second one u r writing the string in the memory allocated using malloc where as in the first case it is else where in the memory and is just pointed by dest.
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
You cannot assign to an array using '=', with or without a trailing 0. When you see a statement like:
Code:
char *myString = "This is the string in question";
you are seeing a compile-time initialization, done as a favor by the compiler. This occurs at compile time; it will not work at run time. See the pointer tutorial referred to in my signature, specifically the section, "Confustoids."