1

Whenever I run the following code, and give input as long string it gets exited with the return value 3221226356

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    int i=0;
    char c,*input;
    input=(char *)malloc(sizeof(char));
    if(input==NULL)
    {
        printf("Could not allocate memory");
        exit(1);
    }
    printf("%d size",strlen(input));
    printf("Enter the string: ");
    while((c=getchar())!='\n')
    {
        realloc(input, (sizeof(char)));
        input[i++]=c;
    }
    printf("%s",input);
}
Rohan Singh Dhaka
  • 173
  • 2
  • 8
  • 33

3 Answers3

6

The realloc function returns a new pointer. It doesn't change the pointer you pass to it.

That means after the first call to realloc you probably start writing to unallocated memory, leading to undefined behavior.

Also note that your realloc call only allocates one byte. You need to allocate the previous size plus one.

There's also the problem of you calling strlen on a pointer to uninitialized memory (of size one by the way), which also leads to undefined behavior.

And since you treat the memory you allocate as a string, you should also allocate space for the string terminator, so the very first allocation should be for two bytes.

Another couple of notes: sizeof(char) is specified to always result in 1. And in C don't cast the result of malloc (and family).

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

The exit code 0xC0000374 is the value returned when heap corruption is detected.

Where you are reallocating, you do not reallocate more values. You free 1 char worth of memory, and then allocate a new 1 char memory segment. This causes input[i++] to access a region outside of the area you allocated.

the6p4c
  • 644
  • 5
  • 17
2

A lot of problems with this code:

  1. You cast the result of malloc, which is unnecessary
  2. You always reallocate only 1 byte with realloc, but even given that, you do not do anything with realloc's return value (which is a resized pointer), so nothing useful happens here
  3. Since you always have a 1-byte allocation to input, you attempt to access memory outside this allocation, which is going to return garbage (if you're lucky enough not to get a seg fault)

Read up on documentation for malloc and realloc to figure out where your code is going wrong.

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345