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. 14 7229 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. 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 -
str = (char *)malloc(sizeof(char)*5);
-
-
str = (char *)calloc(5, sizeof(char));
-
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
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. 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
"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)); 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
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
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
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
THANKS ALL.
I wrote a memo of all your suggests and views , I learned a lot :)
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" 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 ---
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.
"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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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));
/*...
|
by: Rahul Gandhi |
last post by:
Which one is more fast?
malloc followed by memset
or
calloc
|
by: MK |
last post by:
I am a newbie. Please help. The following warning is issued by gcc-3.2.2
compiler (pc Linux):...
|
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 ?
|
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...
|
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?
|
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...
|
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 =...
|
by: Naresh1 |
last post by:
What is WebLogic Admin Training?
WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
|
by: jalbright99669 |
last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
|
by: antdb |
last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine
In the overall architecture, a new "hyper-convergence" concept was...
|
by: Matthew3360 |
last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function.
Here is my code.
...
|
by: AndyPSV |
last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
|
by: Matthew3360 |
last post by:
Hi,
I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...
|
by: Oralloy |
last post by:
Hello Folks,
I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA.
My problem (spelled failure) is with the...
|
by: Carina712 |
last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand....
|
by: Rahul1995seven |
last post by:
Introduction:
In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python...
| |