By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,679 Members | 1,063 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,679 IT Pros & Developers. It's quick & easy.

A question on malloc() and calloc()

P: n/a
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.

Feb 10 '06 #1
Share this Question
Share on Google+
14 Replies


P: n/a
Ro*****@gmail.com wrote:
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.
Feb 10 '06 #2

Banfa
Expert Mod 5K+
P: 8,916
You have a number of errors although not all of them may be contributing to the problem.


The code line

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

is wrong. You have too few parameters in the call to calloc, it's prototype is

void *calloc(size_t nelem, size_t elsize);

See here

Additionally in both cases you are attempting to allocate sizeof(char *)*5 which you then copy the string "abcd" to. The string "abcd" is 5 bytes long, 1 for each letter plus the terminator.

However sizeof(char *)*5 is dependent on sizeof(char *), this is likely to be 4 bytes (but may be lower or higher depending on the target computer system) so you are allocating 20 bytes of data. I think that you probably mean sizeof(char) * 5.

malloc takes the number of bytes you wish to allocate and calloc takes the number of elements and the size of the elements that you wish to allocate (which it then multiples together internally to get the number of bytes).

I think that your malloc and colloc lines should respectively be

Expand|Select|Wrap|Line Numbers
  1.     str = (char *)malloc(sizeof(char)*5);
  2.  
  3.     str = (char *)calloc(5, sizeof(char));
  4.  
Normally I would also advise you to check the value of the pointer str before copying to it having called m/calloc to check that the memory has actually been allocated.

Cheers
Ben
Feb 10 '06 #3

P: n/a
Ro*****@gmail.com wrote:
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.
Feb 10 '06 #4

P: n/a
Ro*****@gmail.com wrote:
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
errors if you forget to #include <stdlib.h>, like you did in this case.
See http://c-faq.com/malloc/mallocnocast.html for details.
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.
------------------------------
1, can work well , but when I execute 2, Segmentation fault happened.
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

Feb 10 '06 #5

P: n/a
"Nils O. Selåsdal" <NO*@Utel.no> wrote in message
news:43********@news.broadpark.no...
Ro*****@gmail.com wrote:
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.


Yes, if you do it like this, you will not have the same problem again:
str = malloc(5*sizeof(*str));
Feb 10 '06 #6

P: n/a
Ro*****@gmail.com 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 !

--
A+

Emmanuel Delahaye
Feb 10 '06 #7

P: n/a

Emmanuel Delahaye wrote:
Ro*****@gmail.com 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);


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...

--
BR, Vladimir

Feb 10 '06 #8

P: n/a
Vladimir S. Oka wrote:

Emmanuel Delahaye wrote:
Ro*****@gmail.com 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);


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"

--
pete
Feb 10 '06 #9

P: n/a
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);

--
A+

Emmanuel Delahaye
Feb 10 '06 #10

P: n/a
THANKS ALL.
I wrote a memo of all your suggests and views , I learned a lot :)

Feb 10 '06 #11

P: n/a
Emmanuel Delahaye wrote:
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);


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"

Feb 10 '06 #12

P: n/a
Ro*****@gmail.com wrote:
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.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Feb 10 '06 #13

P: n/a
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.

Feb 10 '06 #14

P: n/a
"kp********@gmail.com" <kp********@gmail.com> writes:
1 - The required header file was not included in the program(<malloc.h>
or <stdlib.h>) which is necessary for calloc and free functions.
<malloc.h> is not a standard header. Use <stdlib.h>.
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.
--
"Some people *are* arrogant, and others read the FAQ."
--Chris Dollin
Feb 11 '06 #15

This discussion thread is closed

Replies have been disabled for this discussion.