• C

segmetnation fault

#include<stdio.h>

int main() {


 char *buffer;
printf("etner a string");
gets(buffer);
 printf("%s", buffer);
 return 0;
}

getting segmentation fault

how to correct this.
nagaharikolaAsked:
Who is Participating?
 
evilrixSenior Software Engineer (Avast)Commented:
Well, the pointer has to point to an area of memory to which it can store your input. A pointer by itself is nothing other then a reference to a memory location. You need to assign some memory to which the pointer can point too. Either you can do that on the stack as a static array or on the heap using malloc.
0
 
rysicCommented:
char buffer[50]
0
 
nagaharikolaAuthor Commented:
I don't want to declare arrays.
i want to declare  a char pointer and run the program
0
 
MilleniumaireCommented:
char *buffer only declares a pointer to a character buffer, it does not declare or reserve and space in memory in which a character string can be stored.

The description of gets shows:

      gets()         Reads characters from the standard input stream, stdin,
                     into the array pointed to by s, until a new-line
                     character is read or an end-of-file condition is
                     encountered.  The new-line character is discarded and
                     the string is terminated with a null character.

Notice how it says "into the array pointed to by s".  You aren't declaring an array and so there is nowhere for gets to store the string that it processes.

Why don't you want to declare an array?
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> char *buffer only declares a pointer to a character buffer
Sorry to be pedantic but actually, it declares a pointer than can point to char. Whether this has 'buffer' (or string) semantics or not is down to how this pointer is interpreted.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.