S
sindica
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. And how come "Length of str2 after" is 17.
Is it because malloc allocates a minimum chunk of memory (3 here) and
later grow to the demand? Ok agreed, but it grows well beyond the
demand (It grows up to 17 instead of 11).
~saraca
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. And how come "Length of str2 after" is 17.
Is it because malloc allocates a minimum chunk of memory (3 here) and
later grow to the demand? Ok agreed, but it grows well beyond the
demand (It grows up to 17 instead of 11).
~saraca