String - Segmentation Fault

Hi All,

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.

#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 ;
}

name_1 is uninitialized and may be pointing anywhere. You need to allocate some memory and then assign its location to name_1.

Regards,
Alister

1 Like

Is it good that i can declare a pointer and initialize the variable to NULL?
After declaring it to NULL, will the program take input?

---------- Post updated at 01:58 PM ---------- Previous update was at 01:51 PM ----------

char *arr ;
arr = NULL ;
scanf("%s",arr) ;

Is the above code OK?

char *arr=malloc(100);
if(arr==NULL)
{
    perror("Cannot allocate memory");
    exit(1);
}

That is what alister asked you to do. Change the 100 to a suitable size, +1 more byte for the terminating \0 character.

... and remember to free it when you're done.

Yes, see, they're both pointers as far as the computer's concerned.

name_2 ends up being a pointer that points to 20 bytes of memory that can hold a string.

name_1 is a pointer that points nowhere in particular at all, and odds are good it will end up pointing at invalid memory.

Setting it to NULL will guarantee it points to invalid memory.

C doesn't give you memory unless you ask for it.

1 Like