473,385 Members | 2,014 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

A question on malloc() and calloc()

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
14 7422
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
9,065 Expert Mod 8TB
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
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
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
"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
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

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
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
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
THANKS ALL.
I wrote a memo of all your suggests and views , I learned a lot :)

Feb 10 '06 #11
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
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
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
"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: rihad | last post by:
To make up a proper dynamically allocated empty C string, would it suffice to say: return calloc(1, 1); or am I better off using the longer version char *p = malloc(1); if (p) *p = 0;...
29
by: David Hill | last post by:
Is there a difference between: /* code 1 */ struct sample test; test = malloc(sizeof(struct sample)); memset(&test, 0, sizeof(test)); /* code 2 */ struct sample test; test = calloc(1,...
14
by: Rahul Gandhi | last post by:
Which one is more fast? malloc followed by memset or calloc
27
by: MK | last post by:
I am a newbie. Please help. The following warning is issued by gcc-3.2.2 compiler (pc Linux): ================================================================== read_raw_data.c:51: warning:...
37
by: Harsimran | last post by:
Can any one explain what are far pointers and what is the difference between malloc and calloc .Which is better ?
11
by: lohith.matad | last post by:
Hi all, Though the purpose of both malloc() and calloc() is the same, and as we also know that calloc() initializes the alloacted locations to 'zero', and also that malloc() is used for bytes...
8
by: venkatesh | last post by:
hai to everybody, i am having doubt in difference between the malloc and calloc function. please tell where to use and when to use those functions?
318
by: jacob navia | last post by:
Rcently I posted code in this group, to help a user that asked to know how he could find out the size of a block allocated with malloc. As always when I post something, the same group of people...
46
by: lovecreatesbea... | last post by:
Do you prefer malloc or calloc? p = malloc(size); Which of the following two is right to get same storage same as the above call? p = calloc(1, size); p = calloc(size, 1);
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.