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 !!
|
Go4Expert Member
|
|
| 31May2007,03:05 | #2 |
|
Quote:
Originally Posted by vila8 dest = "HiHello\0"; |
|
Light Poster
|
|
| 6Jun2007,01:28 | #3 |
|
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.
|
|
Team Leader
|
![]() |
| 6Jun2007,05:13 | #4 |
|
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"; |

