I have a problem with this code. I am using a gcc compiler and when i compile and execute this code i am getting a seg fault. I am just assigning two variables, name_1 as pointer and name_2 as string. When i am trying to provide string input for the two values i am getting a seg fault. This seg fault is always associated with the pointer variable that i am using.
Below i have provided the code and the screenshot of the error.
#include <stdio.h>
int main()
{
char *name_1 ;
char name_2[10] ;
/* Getting 2 strings as an input from the user
and is stored in the pointer variable name_1 and name_2*/
scanf("%s",name_1) ;
scanf("%s",name_2) ;
/* Printing the values of the varibales
name_1 and name_2 in string format */
printf("\n%s",name_1) ;
printf("\n%s",name_2) ;
printf("\n\n") ;
return 0 ;
}
Please help me in this code.
-Wall
, you'd have received warnings from the compiler about your mistake. Make sure you do compile with (at least)-Wall
if you're using GCC. If you're using some other compiler, then find out how to turn on more warnings. – Jonathan Lefflername_1
was allocated; it is achar *
, so enough space for storing onechar
pointer was allocated. One part of the trouble is that you never initialized the pointer to point to something. Another part of the trouble is thatscanf()
not only assumed that the pointer was initialized, it also assumed it was initialized so that it pointed to an area of memory big enough to store the string to be read byscanf()
, including the terminating null. By changing the definition ofname_1
to, say,char name_1[20]
, you ensure that there are twenty bytes of space for the string. – Jonathan Lefflerchar name_0[20]; char *name_1 = name_0;
then you have allocated space forscanf()
to store the data in, and initializedname_1
to point to that space. However, you can subsequently change your mind and makename_1
point to a different area (egname_2
) if you want to. Which makes most sense depends on what you're going to do withname_1
after you've read the data. – Jonathan Leffler