-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
si*****@gmail.com wrote:
| I am using DevC++ 4.0 lately, which uses Mingw port of GCC, on a
| WinXP. I am surprised to see the malloc behaviour which is not
| consistent with the documentation. See the program and its output
| below.
|
| #include <stdio.h>
| #include <stdlib.h>
|
| int main(int argc, char *argv[])
| {
| char *str1;
| char *str2;
| str1 = "Hello world";
| printf("Length of str1 %d\n", strlen(str1));
| str2 = (char *) malloc(strlen(str1));
| printf("Length of str2 %d\n", strlen(str2));
|
| strncpy(str2, str1, strlen(str1));
| printf("Length of str2 after %d\n", strlen(str2));
|
|
| return 0;
| }
|
| Output is
| Length of str1 11
| Length of str2 3
| Length of str2 after 17
|
| From what i understand from the explanation of malloc, "Length of
| str2" should be 11.
Not the way you compute it, it shouldnt.
malloc() returns a pointer to an uninitialized piece of memory that you can
store a string in.
strlen() counts the number of characters in a character array, stopping at, and
excluding the first '\0' character.
Since you don't initialize the memory that malloc() gives you before you use
strlen() to count the number of characters, you are counting the non-zero
characters that are the residual garbage in the character array pointed to by
the value that malloc() returned. There is no guarantee that there will be a
'\0' character anywhere in that array, or even beyond it, and no guarantee that
the run-time will prevent strlen() from exceeding the bounds of the memory that
was allocated by malloc(). This means that you are potentially counting /beyond/
the confines of the memory allocated by malloc(), or counting short within the
memory block.
In other words, your method is wrong, and your results are wrong because of it.
There is no predetermined 'expected results' for your computation, so 3 is as
valid as 11.
| And how come "Length of str2 after" is 17.
See above. You fouled up the computation with the same design flaw.
One further note; in C, strings are terminated by a '\0' character that isn't
counted by strlen(). Thus, your str1 contains 12 characters, even though
strlen() says that there are 11.
This means that your malloc() is one byte too short to contain the '\0' that's
needed for your third test ("Length fo str2 after") to work properly.
| Is it because malloc allocates a minimum chunk of memory (3 here)
No. See above
[snip]
- --
Lew Pitcher
IT Consultant, Enterprise Data Systems,
Enterprise Technology Solutions, TD Bank Financial Group
(Opinions expressed are my own, not my employers')
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)
iD8DBQFBr0WcagVFX4UWr64RAmSXAKCldZ0/lVk9Gu/Qg/Yq24EezLYSGgCg3Vpy
3uA0cgS7BWXbhV0K7PyR9oU=
=TFwh
-----END PGP SIGNATURE-----