Reputation: 1571
I'm new to C and I have created the following code, but when run the program crashes. Why? How do I stop it crashing?
char *get()
{
char *n;
printf("\n user name : ");
scanf("%s", &n);
return n;
}
int main()
{
char *c = get();
printf("%s", c);
return 0;
}
Upvotes: 0
Views: 1855
Reputation: 263647
scanf
is reading characters from stdin
and storing them in the memory that n
points to. You haven't initialized n
to point to anything, so scanf
is probably trying to store your input in some arbitrary location in memory. You're lucky that it crashed rather than quietly acting as if it were working correctly.
Returning a string from a C function is more complex than you might expect.
There are (at least) three general approaches:
Require the caller to pass in a pointer to (the first element of) an array into which the string is to be stored, along with another argument telling the function how big the array is. This can require error handling if the array isn't big enough to hold the result.
Declare a static
array inside the function and return a pointer to it. (You can't return a pointer to a non-static local array, since the array ceases to exist when the function returns.) Problems: Multiple calls use the same storage space (particularly problematic in the presence of threading), and the allocated size is fixed.
Allocate the result inside the function using malloc()
. This requires the caller to free()
the result.
Recommended reading: the comp.lang.c FAQ. In particular, question 7.5b is nearly a direct answer to your question (and would have saved me some typing if I'd realized it earlier). (I don't usually link to individual questions because I like to encourage people to browse.)
EDIT: Also, scanf
with an unqualified "%s"
format is inherently unsafe. It will attempt to store however many characters are entered in the array; there's no way to avoid buffer overruns (say, if your cat sits on the keyboard). @Artefacto referred to this problem in the link in the comment.
Upvotes: 3
Reputation: 181
First of all you musst allocate memory for your string
you can dynamically doing it by using malloc;
for example with a size of 200 :
#include <stdlib.h>
char (*n)[200] = malloc(sizeof *n);
don't forget to liberate the pointer with
free(n);
Upvotes: 1
Reputation: 67574
In C it is typical for the parent to handle memory allocation since there's no garbage collector to clean up after yourself, so it has to do that anyway:
void get(char *n)
{
printf("\n user name : ");
scanf("%s", n);
}
int main()
{
char c[200];
get(c);
printf("%s", c);
return 0;
}
Upvotes: 4