473,554 Members | 2,921 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,"abc d");
str[0] = 's' ;

printf("%s\n",s tr);
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,"abc d");
str[0] = 's' ;

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

7 str = (char *)calloc(sizeof (char *)*5);
(gdb) s
8 strcpy(str,"abc d");
(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 7461
Ro*****@gmail.c om 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,"abc d");
str[0] = 's' ;

printf("%s\n",s tr);
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,"abc d");
str[0] = 's' ;

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

7 str = (char *)calloc(sizeof (char *)*5);
(gdb) s
8 strcpy(str,"abc d");
(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 Recognized Expert Moderator Expert
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.c om 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,"abc d");
str[0] = 's' ;

printf("%s\n",s tr);
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,"abc d");
str[0] = 's' ;

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

7 str = (char *)calloc(sizeof (char *)*5);
(gdb) s
8 strcpy(str,"abc d");
(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(c har) * 5). What you
did, malloc(sizeof(c har *) * 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(c har *) * 5) // Will allocate 20 or 40 bytes.

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

Secondly, about calloc(). The man page for calloc() says that is
"calloc(siz e_t count, size_t size)", this translates to mean
"calloc(how_man y, 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.c om 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,"abc d");
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",s tr);
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,"abc d");
str[0] = 's' ;

printf("%s\n",s tr);
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.c om 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.c om 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.c om 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.c om 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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
4871
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; return p;
29
40354
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, sizeof(struct sample));
14
6489
by: Rahul Gandhi | last post by:
Which one is more fast? malloc followed by memset or calloc
27
4719
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: assignment makes pointer from integer without a cast ================================================================== when the following piece of...
37
2536
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
5770
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 allocation whereas calloc() for chunk of memory allocation. Apart from these is there any strong reason that malloc() is prefered over calloc() or...
8
11167
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
12795
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 started to try to find possible errors, a harmless passtime they seem to enjoy. One of their remarks was that I used "int" instead of "size_t"...
46
3627
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
7600
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7521
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7802
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7563
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7889
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
3560
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2020
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1134
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
841
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.