I have written the following code in C. I need to understand how the string copy operations will be performed after the character pointer gets assigned memory via malloc()
dynamically.
My code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFSZ 20
int main()
{
char *name = NULL;
char my_name[BUFFSZ] ;
memset(my_name,0,BUFFSZ);
strcpy(my_name, "vinothkumarsaradavallivaradathirupathi");
printf("string copied is %s\n",my_name);
if ((name = malloc(1 + strlen(my_name)+1)) != NULL)
strcpy(name,my_name);
printf("Name is %s\n",name);
free(name);
name = NULL;
return 0;
}
Actual output:
string copied is vinothkumarsaradavallivaradathirupathi
Name is vinothkumarsaradavalliva��
According to the code, I have expected the output below but got only one above. It will be helpful if someone explains this clearly.
Expected output:
string copied is vinothkumarsaradaval
Name is vinothkumarsaradaval
When I ran this code in GDB, I got the following output:
Breakpoint 2, main () at first_pgm.c:12
12 memset(my_name,0,BUFFSZ);
(gdb) n
14 strcpy(my_name, "vinothkumarsaradavallivaradathirupathi");
(gdb) p name
$1 = 0x0
(gdb) p my_name
$2 = '\000' <repeats 19 times>
(gdb) n
Breakpoint 3, main () at first_pgm.c:15
15 printf("string copied is %s\n",my_name);
(gdb) p my_name
$3 = "vinothkumarsaradaval"
(gdb) n
string copied is vinothkumarsaradavallivaradathirupathi
Here, why "$3" and "string copied" outputs are conflicting?