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