Lynx
Lynx

Reputation: 13

realloc() invalid pointer error when increasing size of string in a function

When i run code it show realloc() invalid pointer error.

Is anything wrong in input() function?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
char *input(void)
{
    int n = 1;
    char *str = malloc(sizeof(char));
    *str = '\0';
    while((*str=getchar())!='\n')
    {
        n++;
        str = realloc(str,sizeof(char)*n);
        str++;
    }
    return str;
}

int main(int argc, char const *argv[])
{
    char *str = input();
    printf("%s",str);
    free(str);
    return 0;
}

Upvotes: 0

Views: 1472

Answers (3)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

You make a few errors:

  • you return the end of the string, not the beginning.

  • realloc needs the original address (see Thomas' answer)

  • realloc may return a new address

  • you do not terminate the string.

The following fixes these errors and includes some suggestions:

char *input(void)
{
    size_t i=0;
    int c;
    char *str = malloc(1);
    if (!str) return 0;
    while((c=getchar())!=EOF && c!='\n')
    {
        str[i]= c;
        if ((newstr = realloc(str,i+1))==0)
            break;          // out of memory: return what we have
        str= newstr;
        i++;
    }
    str[i]= '\0';
    return str;
}

Upvotes: 4

alk
alk

Reputation: 70901

An approach with no redundant calls and complete error checking:

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

char *input(void)
{
  size_t n = 0;
  char * str = NULL;

  do
  {
    ++n;

    {
      void * pv = realloc(str, (n + 1) * sizeof *str);
      if (NULL == pv)
      {
        perror("realloc() failed");

        break;
      }

      str = pv;
    }

    {
      int result = getchar();

      if (EOF == result)
      {
        if (ferror(stdin))
        {
          fprintf(stderr, "getchar() failed\n");
        }

        --n;

        break;
      }

      str[n - 1] = result;
    }
  } while ('\n' != str[n - 1]);

  if (NULL != str)
  {
    str[n] = '\0';
  }

  return str;
}

int main(int argc, char const *argv[])
{
  int result = EXIT_SUCCESS; /* Be optimistic. */

  char * str = input();
  if (NULL == str)
  {
    result = EXIT_FAILURE;

    fprintf(stderr, "input() failed\n");
  }
  else
  {
    printf("input is: '%s'\n", str);
  }

  free(str);

  return result;
}

Upvotes: 0

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

After doing str++, the pointer no longer points to the start of the allocated string. realloc needs the original pointer, not one that points to somewhere inside the allocated data.

Upvotes: 2

Related Questions