A question on malloc() and calloc()

R

Roka100

Hi all,
I tried 2 programs :

#include <stdio.h>
#include <string.h>

1,
int main(void){
char *str = NULL;

str = (char *)malloc(sizeof(char *)*5);
strcpy(str,"abcd");
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}
------------------------------
2,
#include <stdio.h>
#include <string.h>

int main(void){
char *str = NULL;

str = (char *)calloc(sizeof(char *)*5);
strcpy(str,"abcd");
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}
------------------------------
1, can work well , but when I execute 2, Segmentation fault happened.
Exactly at strcpy(str,"abcd");

7 str = (char *)calloc(sizeof(char *)*5);
(gdb) s
8 strcpy(str,"abcd");
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x42079df6 in strcpy () from /lib/tls/libc.so.6

I thought the difference between calloc and malloc is that calloc()
will initial pointer with NULL or 0. But that does related with the
answer above.??

Thanks.
 
?

=?ISO-8859-1?Q?=22Nils_O=2E_Sel=E5sdal=22?=

Hi all,
I tried 2 programs :

#include <stdio.h>
#include <string.h>
Forgot to include stdlib.h - that's where the malloc/calloc
functions are declared.
1,
int main(void){
char *str = NULL;

str = (char *)malloc(sizeof(char *)*5);
Avoid uneeded casts, like for the return of malloc.
Also remember to check the return value, it might
return NULL on error.

You allocate space for 5 char pointers.
Likely you only need to allocate space for
5 chars. Since sizeof(char) is 1, it'll just be

str = malloc(5);
strcpy(str,"abcd");
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}
------------------------------
2,
#include <stdio.h>
#include <string.h>

int main(void){
char *str = NULL;

str = (char *)calloc(sizeof(char *)*5);

calloc takes 2 arguments.

Read up on the malloc and calloc documentation.
Since it appears you're on a linux machine - run
man calloc
str = calloc(5,1);
strcpy(str,"abcd");
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}
------------------------------
1, can work well , but when I execute 2, Segmentation fault happened.
Exactly at strcpy(str,"abcd");

7 str = (char *)calloc(sizeof(char *)*5);
(gdb) s
8 strcpy(str,"abcd");
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x42079df6 in strcpy () from /lib/tls/libc.so.6

I thought the difference between calloc and malloc is that calloc()
will initial pointer with NULL or 0. But that does related with the
answer above.??

Maybe the wrong use of calloc - it takes 2 arguments and/or the
forgotten #include <stdlib.h> ?

I'm assuming you're using gcc in which case you should /atleast/ compile
with the -Wall flag to gcc.
 
P

Patrick M. Rutkowski

Hi all,
I tried 2 programs :

#include <stdio.h>
#include <string.h>

1,
int main(void){
char *str = NULL;

str = (char *)malloc(sizeof(char *)*5);
strcpy(str,"abcd");
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}
------------------------------
2,
#include <stdio.h>
#include <string.h>

int main(void){
char *str = NULL;

str = (char *)calloc(sizeof(char *)*5);
strcpy(str,"abcd");
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}
------------------------------
1, can work well , but when I execute 2, Segmentation fault happened.
Exactly at strcpy(str,"abcd");

7 str = (char *)calloc(sizeof(char *)*5);
(gdb) s
8 strcpy(str,"abcd");
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x42079df6 in strcpy () from /lib/tls/libc.so.6

I thought the difference between calloc and malloc is that calloc()
will initial pointer with NULL or 0. But that does related with the
answer above.??

Thanks.

You've made two very very grave errors, I'll tell you exactly what you
did wrong, so pay close attention. First of all, disregarding the
differences between calloc() and malloc(), when you want to allocate
space for 5 characters you should run malloc(sizeof(char) * 5). What you
did, malloc(sizeof(char *) * 5), allocates 20 or 40 bytes of memory
(dependent on the CPU), not 5. "char *" is a pointer to char, a pointer
to char is either 4bytes big (on a 32bit CPU) or 8bytes big (on a 64bit
CPU). However, sizeof(char) is 1byte big, which is what you want there.
In conclusion:

Bad:
malloc(sizeof(char *) * 5) // Will allocate 20 or 40 bytes.

Good:
malloc(sizeof(char) * 5) // Will allocate 5 bytes.

Secondly, about calloc(). The man page for calloc() says that is
"calloc(size_t count, size_t size)", this translates to mean
"calloc(how_many, how_big)". Let's say that you have a "struct
crackerjacks" that is 20bytes big, and you want to allocate enough
memory for 100 crackerjacks, you could call "calloc(100, sizeof(struct
crackerjacks))"; or if you wanted enough memory for 10 chars, you could
do calloc(10, sizeof(char)).

And yes, as you mentioned, calloc() does in fact fill the memory with 0,
unlike malloc.

If you ever want any live advice about C, look me up on AIM, my screen
name is rutski89.
 
R

Robert Gamble

Hi all,
I tried 2 programs :

#include <stdio.h>
#include <string.h>

1,

I assume this line is not part of your program.
int main(void){
char *str = NULL;

str = (char *)malloc(sizeof(char *)*5);

Do not cast the return value of malloc, it is unneccessary and can mask
like you did in this case. said:
strcpy(str,"abcd");

You are storing 5 chars in the space you just allocated for 5 pointers
to char. You should allocate space for 5 chars instead:

str = malloc(sizeof(*str)*5);
or just:
str = malloc(5);
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}
------------------------------
2,
#include <stdio.h>
#include <string.h>

int main(void){
char *str = NULL;

str = (char *)calloc(sizeof(char *)*5);

calloc takes two arguments, not one. You forgot to #include <stdlib.h>
so the compiler didn't notice the prototype mismatch and your casting
of the return value also helped hide that fact.
strcpy(str,"abcd");
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}

All the same comments from the first example apply here as well.

You should also check the return value of malloc/calloc as they can
return NULL if allocation fails which you must not dereference.

Both examples exhibit undefined behavior so anything can happen, and it
did. Fix the items I mentioned above and you should be okay.

[snip]
I thought the difference between calloc and malloc is that calloc()
will initial pointer with NULL or 0. But that does related with the
answer above.??

Malloc allocates space for a specified number of bytes, calloc
allocates space a given number of elements, each of a given size, and
all the bits to zero in the allocated space.
I suggest you check out the documentation that came with your
implementation (maybe man calloc, etc.) or pick up a good book on C.

Robert Gamble
 
S

stathis gotsis

Nils O. Selåsdal said:
Forgot to include stdlib.h - that's where the malloc/calloc
functions are declared.

Avoid uneeded casts, like for the return of malloc.
Also remember to check the return value, it might
return NULL on error.

You allocate space for 5 char pointers.
Likely you only need to allocate space for
5 chars.

Yes, if you do it like this, you will not have the same problem again:
str = malloc(5*sizeof(*str));
 
E

Emmanuel Delahaye

(e-mail address removed) a écrit :
#include <stdio.h>
#include <string.h>

int main(void){
char *str = NULL;

str = (char *)malloc(sizeof(char *)*5);

Rather than writing complicated and buggy pcode, try simplicity :

#include <stdlib.h>

char *str = malloc(sizeof *str * 5);

It rocks !
 
V

Vladimir S. Oka

Emmanuel said:
(e-mail address removed) a écrit :

Rather than writing complicated and buggy pcode, try simplicity :

#include <stdlib.h>

char *str = malloc(sizeof *str * 5);

I must say, I find this hard to read. What's wrong with judicious use
of parenthesis:

char *str = malloc((sizeof *str) * 5);

Just a personal preference...
 
P

pete

Vladimir said:
I must say, I find this hard to read. What's wrong with judicious use
of parenthesis:

char *str = malloc((sizeof *str) * 5);

Just a personal preference...

For string allocation,
I prefer either length plus one,
or sizeof array.

char *str = malloc(strlen("abcd") + 1);
char *str = malloc(sizeof "abcd");

I tend to avoid situations where I find myself poking
my finger at the screen while reciting numerals.

"1 2 3 4 5"
 
E

Emmanuel Delahaye

Vladimir S. Oka a écrit :
I must say, I find this hard to read. What's wrong with judicious use
of parenthesis:

char *str = malloc((sizeof *str) * 5);

Ok, try this:

char *str = malloc (5 * sizeof *str);
 
V

Vladimir S. Oka

Emmanuel said:
Vladimir S. Oka a écrit :

Ok, try this:

char *str = malloc (5 * sizeof *str);

Yes, that looks good, too. I'd still parenthesise `sizeof` part, though
(but that's just me). ;-)

--
BR, Vladimir

"The sooner all the animals are dead, the sooner we'll find their
money."
-- Ed Bluestone, "The National Lampoon"
 
J

Joe Wright

Hi all,
I tried 2 programs :

#include <stdio.h>
#include <string.h>

1,
int main(void){
char *str = NULL;

str = (char *)malloc(sizeof(char *)*5);
strcpy(str,"abcd");
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}
------------------------------
2,
#include <stdio.h>
#include <string.h>

int main(void){
char *str = NULL;

str = (char *)calloc(sizeof(char *)*5);
strcpy(str,"abcd");
str[0] = 's' ;

printf("%s\n",str);
free(str);
return 0;
}
------------------------------
1, can work well , but when I execute 2, Segmentation fault happened.
Exactly at strcpy(str,"abcd");

7 str = (char *)calloc(sizeof(char *)*5);
(gdb) s
8 strcpy(str,"abcd");
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x42079df6 in strcpy () from /lib/tls/libc.so.6

I thought the difference between calloc and malloc is that calloc()
will initial pointer with NULL or 0. But that does related with the
answer above.??

Thanks.
Allow me to re-write one of the programs for you, without comment. See
if you can spot the fixes.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
char *str;
str = malloc(5 * sizeof *str);
strcpy(str, "abcd");
str[0] = 's';
puts(str);
free(str);
return 0;
}

I'll leave the second one to you. Note that calloc() takes two arguments.
 
K

kp.discuss

Hi,
I could see 2 mistakes in ur program (2).

1 - The required header file was not included in the program(<malloc.h>
or <stdlib.h>) which is necessary for calloc and free functions.

2 - calloc takes 2 arguments. 'Number of elements' and 'Length in bytes
of each element'. U missed the arg2(U could have found this error if
the header file was included). Since the second argument is not given,
it was considered 0 and no memory for allocated. Now u are trying to
write to a null pointer with the strcpy function, which has caused the
segmentation fault.
 
B

Ben Pfaff

1 - The required header file was not included in the program(<malloc.h>
or <stdlib.h>) which is necessary for calloc and free functions.

2 - calloc takes 2 arguments. 'Number of elements' and 'Length in bytes
of each element'. U missed the arg2(U could have found this error if
the header file was included). Since the second argument is not given,
it was considered 0 and no memory for allocated.

Omitted arguments aren't necessarily considered to be zero.
Instead, undefined behavior is invoked. In practice, zero is
fairly likely because zero is commonly found in arbitrary memory
locations, but it would be foolish to expect that.
Now u are trying to write to a null pointer with the strcpy
function, which has caused the segmentation fault.

Undoubtedly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top