Strings and string functions in C

I wrote the following:

#include <stdio.h> #include <string.h> char* getString(); char* getString(){ char str[10]; gets(str); return str; } int main() { char* s; s=getString(); strcpy(s,"Hi"); puts(s); return 0; }

I know that the length of str must be less than 10, but even when I wrote just "Hi", nothing was being printed. as far as I see it, it should be Ok. the compiler says that fgets is dangerous and should not be used.

What is the reason that nothing being printed on the screen?


char str[10]; // ... return str;

This is <strong>wrong!!!</strong> Local variables are invalidated when their scope exits; thus using returned array is undefined behavior. You have to malloc a string and return it:

return strdup(str);


Problem pertaining to result have already being discussed. List of solutions that you can do includes:

1). define str globally as "char str[10]" and use it in function main and getString

2). Use malloc/calloc in function getString, code goes something like this...

char* getString(){ char *str = NULL; str = (char *)calloc(10, sizeof(char)); gets(str); return str; } int main() { char* s; s=getString(); strcpy(s,"Hi"); puts(s); free(s); return 0; }`

3). use static for ready help. But it is not conceptually correct approach

e.g. declare as follows in function getString

static char str[10];


The simplest way of getting your code working, though not necessarily the best way, is to make str static.


static char str[10];


Well str[10] is a an array of 10 characters allocated on the <strong>stack</strong>. The stack is removed after the function is out of scope. Hence the address that was returned by the function getString() is no longer valid.

Consider declaring a pointer char *str and dynamically allocating memory with malloc. Now your variable points to a location in the <strong>heap</strong> which continues to remain even after the function has finished executing.

Hope it answered your question


  • Why std::vector iterator is invalidated after the erase() call?
  • Using pointers to write to a std container
  • session.invalidate() not working in Websphere Application Server
  • session.invalidate() not working in Websphere Application Server
  • pthread_create memory leak
  • How does a C++ library implementation allocate memory but not free it when the program exits?
  • Spring batch error tolerance
  • PHP Queue System with Codeigniter. HOW? [closed]
  • Using an STL Iterator without initialising it
  • Compare struct to a constant in C
  • Wrong labels when plotting a time series pandas dataframe with matplotlib
  • Using $compile in a directive triggers AngularJS infinite digest error
  • Updating Dojo provide
  • Getting error 'Cannot read property 'document' of undefined' while importing exp
  • ThreadStatic in asynchronous ASP.NET Web API
  • Default parameter as generic type
  • Android application: how to use the camera and grab the image bytes?
  • ADO and msqli connections very slow
  • custom UITableViewCell with image for highlighting
  • Caching attributes in superclass
  • PHP buffered output depending on server setting?
  • Is it possible to access block's scope in method?
  • Meteor: Do Something On Email Verification Confirmation
  • SignalR .NET Client Invoke throws an exception
  • QLineEdit password safety
  • Accessing IRQ description array within a module and displaying action names
  • How to extract text from Word files using C#?
  • Javascript Callbacks with Object constructor
  • Where to put my custom functions in Wordpress?
  • Rearranging Cells in UITableView Bug & Saving Changes
  • RestKit - RKRequestDelegate does not exist
  • bootstrap to use multiple ng-app
  • WPF Applying a trigger on binding failure
  • Benchmarking RAM performance - UWP and C#
  • Angular 2 constructor injection vs direct access
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Does armcc optimizes non-volatile variables with -O0?
  • costura.fody for a dll that references another dll
  • Conditional In-Line CSS for IE and Others?