• C

segmetnation fault


int main() {

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

getting segmentation fault

how to correct this.
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.
char buffer[50]
nagaharikolaAuthor Commented:
I don't want to declare arrays.
i want to declare  a char pointer and run the program
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?
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.
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.