below is my code
#include <stdio.h>
#include <string.h>
char* get_string(char* question);
int main(void)
{
char* name = get_string("Enter a name:");
printf("%s\n", name);
return 0;
}
char* get_string(char* question)
{
printf("%s", question);
char* input;
scanf("%s", input);
return input;
}
It compiles just fine without any warning or errors, but when I run the code I got this
Bus error: 10
In your function get_string()
you try to take input using scanf()
using a uninitialized pointer called input
.
Since input
points to nothing, reading into it causes undefined behaviour.
To fix it you should allocate memory for your string:
char *input = malloc(sizeof(char) * input_size);
Also don't forget to free()
your input
buffer when you are done using it:
free(input);