0

I am trying to dynamically allocate memory for this C program I have constructed which takes a single string input and reverses it then prints the reversed output. I am very new to C and am unsure on how to use malloc to allocate memory for specified user input. This is the current code I have, we are running these programs in linux, using gcc code.c -o code to compile. Where the file is named code.c

int main(void)
{
    char input[256];
    char temp;
    int i = 0, j = 0;
    scanf("%s", input);
    j = strlen(input) - 1;

    while (i < j)
    {
        temp = input[j];
        input[j] = input[i];
        input[i] = temp;
        i++;
        j--;
    }
    printf("Reverse = %s", input);
    return 0;
}
Puck
  • 2,080
  • 4
  • 19
  • 30
Mgert33
  • 83
  • 10
  • 3
    You want `i++; j--;` ... BTW there is no allocation (`malloc()` and friends) in your code; and no allocation needed. – pmg Aug 17 '20 at 12:03
  • 3
    There's no malloc in your code. – nicomp Aug 17 '20 at 12:04
  • 1
    @Mgert33 Instead of int main{ you have to write int main( void ) { – Vlad from Moscow Aug 17 '20 at 12:06
  • im aware there is no malloc in my code as im unsure how to implement malloc, would you be able to show me how it should be implemented such that it allocates memory for the user input @nicomp – Mgert33 Aug 17 '20 at 12:09
  • @pmg sorry that was a typo, i have it as j-- in mine, all fixed. – Mgert33 Aug 17 '20 at 12:12
  • 1
    Suggestions in comments are not intended to be directives for you to change the content of your post. Once the post is posted, it should only be edited to improve formatting and readability, or to _add_ new content that will clarify the main messages of your post, but never edit existing code. Leave errors that are inherently there when you post it. Otherwise It confuses the issues you are trying to get help with. – ryyker Aug 17 '20 at 12:32

4 Answers4

1

For a malloc implementation you just need to replace

char input[256];

with

char* input = malloc(256);

if(input == NULL){
    //uppon bad allocation NULL will be returned by malloc
    perror("malloc");
    return EXIT_FAILURE;
}

Since malloc needs the allocated space in bytes normally you would multiply the needed space by the type of variable:

char *input = malloc(256 * sizeof *input);

but, since the size of a char is always 1 byte, in this case you won't need it.

The rest of the code can be the same, then after you use input you can/should free the allocated memory:

free(input);

You will need to #include <stdlib.h>.


Side note:

To avoid buffer overflow it's recommmended that you define a maximum size for scanf specifier which sould be at most the size of the buffer:

scanf("%255s", input);

or to also parse spaces:

scanf("%255[^\n]", input);

Notice that there is one less space, which is reserved for the null terminator, automatically added by scanf and mandatory for the char array to be treated as a string.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
0

Once you get a string from user, you can allocate memory like this. malloc() returns a pointer to allocated memory, or NULL if it failed.

size_t input_len = strlen(input);
char* mem_data = malloc(input_len + 1);  // +1 for null-terminate
if(!mem_data)
{
  // failed to allocate memory. do dome error process
}

Following code is copying input reversely to the allocated memory.

int i;
for (i = 0; i < input_len; ++i)
{
    mem_data[i] = input[input_len - i - 1];
}
mem_data[input_len] = 0;  // null terminate

printf("Reverse = %s", mem_data);

Remember, dynamically allocated memory should be free()d after use.

free(mem_data);  // never forget to free memory when you finished using.
John Park
  • 1,644
  • 1
  • 12
  • 17
0

To dynamically allocate space in c you need to know beforehand exactly how much space you want to allocate. So, allocate space exactly same size as input string, you need to take length of the string as input. Sample code will be like below:

int n;
char* input;
int main(){
   scanf("%d",&n);
   input= (char*)malloc((n+1)*sizeof(char));
   scanf("%s",input);
   return 0;
}

You can read about dynamic memory allocation here https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/

  • 1
    `input= (char*)malloc((n+1)*sizeof(char));` -> `input= malloc((n+1));` ( `sizeof(char)` is always 1 by definition. And [do not cast the return of malloc() in C](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). ) The link you posted is incorrect on this point. – ryyker Aug 17 '20 at 12:38
0

The approach that is more often used in books on C for beginners is writing a function that reads character by character from the input stream and reallocates memory dynamically when a new character is read.

Something like the function shown in this demonstrative program below

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * getline( size_t n )
{
    char *s = NULL;
    
    if ( n != 0 )
    {
        s = malloc( sizeof( char ) );
        size_t i = 0;
        
        for ( int c; i < n - 1 && ( c = getchar() ) != EOF && c != '\n'; ++i )
        {
            s = realloc( s, i + 2 );

            if ( s == NULL ) break;
            
            s[i] = c;
        }
        
        if ( s ) s[i] = '\0';
    }
    
    return s;
}

char * reverse( char *s )
{
    if ( *s != '\0' )
    {
        for ( size_t i = 0, j = strlen( s ); i < --j; i++ )
        {
            char c = s[i];
            s[i] = s[j];
            s[j] = c;
        }
    }       
    
    return s;
}


int main(void) 
{
    const size_t N = 256;
    printf( "Enter a string (no more than %zu symbols): ", N );
    
    char *s = getline( N );
    
    if ( s ) printf( "The reversed string is \"%s\"\n", reverse( s ) );
    
    free( s );
    
    return 0;
}

The program output might look like

Enter a string (no more than 256 symbols): Hello Mgert33
The reversed string is "33tregM olleH"
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335