I'm trying to accept arbitrary length strings from stdin. I know that you can't do that automatically in C, so I ask the user to input the size of each string, allocate the memory for it, and then read the string.
Unfortunately, it doesn't work properly. I've included a sample run below.
How long is your source string?
3
Please enter your source string.
123
How long is your search string?
6
Please enter your search string.
123456
Now searching string "56" for characters "123456".
Segmentation fault
Thanks in advance for any help!
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *source_string = NULL;
char *search_string = NULL;
int source_length = 0, search_length = 0;
puts("How long is your source string?");
scanf("%d", &source_length);
source_string = (char *)malloc(source_length + 1);
puts("Please enter your source string.");
scanf("%s", &source_string);
puts("How long is your search string?");
scanf("%d", &search_length);
search_string = (char *)malloc(search_length + 1);
puts("Please enter your search string.");
scanf("%s", &search_string);
printf("Now searching string \"%s\" for characters \"%s\".\n", &source_string, &search_string);
puts("Cleaning up memory...");
free(source_string);
free(search_string);
return EXIT_SUCCESS;
}
How long is your source string?
3
Please enter your source string.
123
How long is your search string?
6
Please enter your search string.
123456
Now searching string "56" for characters "123456".
Segmentation fault
Thanks in advance for any help!
Comment