Search code examples
cfunctionpointersdynamic-allocation

C code behaves differently as a main, as a called function


I am writing a program that processes users text. First i wrote all the functions as different mini-programs consisting of only main-func and everything worked perfectly. But now assembling all the code i got stuck, because one function behaves differently. This function is used to get input text from user and place it into dynamically allocated memory. The input ends when "END" string is entered.

first it was:

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

int main()
{
  char** text = NULL;
  int i,j,flag=1;
  int count_strings;
  char c;

  for(i=0;flag;i++)
  {
    text = (char**)realloc(text,sizeof(char*)*(i+1));
    *(text+i) = NULL;
    c = 0;
    for(j=0;c!='\n';j++)
    {
      c = getchar();
      *(text+i) = (char*)realloc(*(text+i),sizeof(char)*(j+1));
      *(*(text+i)+j) = c;
    }
    *(*(text+i)+j-1) = ' ';
    *(*(text+i)+j) = '\0';

    if(strcmp(*(text+i),"END ")==0)
    {
      flag = 0;
      free(*(text+i));
    }
  }
  count_strings = i-1;

  for(i=0;i<count_strings;i++)
  {
    printf("%d.%s\n",i,*(text+i));
    free(*(text+i));
  }
  free(text);
}

and it worked like this:

input:
aaaa
bbbb
cccc
dddd
eeee
END
output:
0.aaaa 
1.bbbb 
2.cccc 
3.dddd 
4.eeee 

But when i tried to make it a callable function it started behaving in a different way.

char** text_input(int* count_strings)
{
  char** text = NULL;
  int i,j,flag=1;
  char c;

  for(i=0;flag;i++)
  {
    text = (char**)realloc(text,sizeof(char*)*(i+1));
    *(text+i) = NULL;
    c = 0;
    for(j=0;c!='\n';j++)
    {
      c = getchar();
      *(text+i) = (char*)realloc(*(text+i),sizeof(char)*(j+1));
      *(*(text+i)+j) = c;
    }
    *(*(text+i)+j-1) = ' ';
    *(*(text+i)+j) = '\0';

    if(strcmp(*(text+i),"END ")==0)
    {
      flag = 0;
      free(*(text+i));
    }
  }
  *count_strings = i-1;
  for(i=0;i<*count_strings;i++)
    printf("%d.%s\n",i,*(text+i));
  return(text);
}

Example:

input:
aaa
bbb
ccc
ddd
eee
END
output:
0. 
1.aaa 
2.bbb 
3.ccc 
4.ddd 
5.eee 

Solution

  • If the code is the same, what has probably changed is the input.

    You might have had a new line character already in the input stream before calling your function. Make sure that the previous code consumes all the input before proceeding.