chiranjeevi_dk
chiranjeevi_dk

Reputation: 1

What realloc() actually does in this code?

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

int main() {

    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    // s = realloc(s, strlen(s) + 1);
    for(int i=0;i<strlen(s);i++)
    {
        if(s[i]==' ')
           printf("\n");
        else {
        printf("%c",s[i]);
        }
    }
   
    return 0;
}

this is a problem from hackkerank though i commented realloc() the program worked fine i thought i wouldnt work! i was curious what realloc() does, btw im currently learning pointer basic.

Upvotes: 0

Views: 122

Answers (4)

Andreas Wenzel
Andreas Wenzel

Reputation: 25326

The function malloc first allocates enough space for 1023 characters in addition to the terminating null character. However, since the input is likely much smaller, this is probably a waste of memory. The function call to realloc reduces the amount of allocated memory to the amount actually required, thereby freeing the unneeded memory.

By not calling realloc, you are therefore probably wasting a few hundred bytes of memory. But wasting such a small amount of memory will generally not cause your program to fail, unless you do this many times in your program (for example in a loop).

Upvotes: 1

hazel
hazel

Reputation: 1

In the code you provided, the line that was commented out was an attempt to resize the block of memory that the pointer is pointing to to just enough to fit the string and an extra null character. This is usually to ensure that the string is terminated correctly, as the allocated memory does not automatically set the terminating null character. However, even if you don't use the , your code will work correctly because when you use the Read input, the function automatically adds a null character to the end of the string. As a result, the string is correctly terminated even if it is not called.

Upvotes: 0

Schwern
Schwern

Reputation: 165396

realloc REALLOCates memory. It can grow, shrink, or completely replace the allocated memory.

char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);

This code allocates a buffer of 1024 bytes. Then it reads input into that buffer. Then it shrinks the buffer to the size of the string (plus the null byte necessary to mark the end of strings in C), freeing the rest of the memory. This is a common pattern when reading input: allocate a large input buffer, then either copy the memory or shrink the buffer. It's not necessary, but it saves memory, especially if you're reading a lot of small lines.

Note 1: I say "shrinks", but realloc might instead allocate new memory and free the old memory. This is why you must always use the returned pointer from realloc.

Note 2: this is not a safe operation because scanf can read more than 1024 bytes overflowing the buffer. To be safe it should have limited it: scanf("%1023[^\n]", s);, 1023 bytes plus the null byte.

Note 3: If you want to read a line, use fgets.

Note 4: for(int i=0;i<strlen(s);i++) scans the string twice. Once by strlen to find the null byte, and again by the for loop. for(int i=0; s[i] != '\0'; i++) scans once ending when it sees the null byte.

Note 5: As pointed out in the comments, the code fails to check if the scanf succeeded. If it failed, s will contain garbage. strlen(s) will search that garbage for a null byte. It could return some nonsense, or it might try to walk off the allocated memory and cause an error. realloc and malloc can also fail (although that's rarer) and need to be checked.

Upvotes: 3

arch
arch

Reputation: 764

See https://en.cppreference.com/w/c/memory/realloc . realloc does shrink the memory to the required space here, so the rest of the allocated 1024 bytes can be used by a future malloc-call.

PS: As the program does exit after a quite short time afterwards, it may not be worth.

Upvotes: 2

Related Questions