Dynamic allocation for text input

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Hengist
    New Member
    • Feb 2008
    • 2

    Dynamic allocation for text input

    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.

    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;
    }
    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!
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Check this.
    I have corrected few issues in the code
    [code=c]
    #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_stri ng, &search_string) ;
    printf("Now searching string \"%s\" for characters \"%s\".\n", source_string, search_string);

    puts("Cleaning up memory...");
    free(source_str ing);
    free(search_str ing);

    return EXIT_SUCCESS;
    }
    [/code]

    Raghuram

    Comment

    • Hengist
      New Member
      • Feb 2008
      • 2

      #3
      I can't believe I missed that. <shakes head>
      It works perfectly now. Thank you for your help!

      Comment

      Working...