-1
#include <stdio.h>

int main(){

    char *p, *initial;
    int c, in=0;

    for(initial=p; (c = getchar()) != EOF; p++, in++)
        *p = c;

    for(int i=0; i<in; i++)
        printf("%p = %c\n", initial, *initial++);
}

For an input like hello hai, the program gives incomplete output:

0028FF29 = h
0028FF2A = e
0028FF2B = l
0028FF2C = l
0028FF2D =  
0028FF2E =  
0028FF2F =  
0028FF30 =  
0028FF31 =

It is working fine for small text, but it's not working for large text.

Rushat Rai
  • 743
  • 2
  • 15
  • 31
Atul
  • 546
  • 4
  • 16

1 Answers1

3

Undefined behavior. You don't set p to point to any valid memory location. So *p = c does not a well defined program make.

You can either have p point to a fixed sized buffer (if you know input will never be beyond a certain number of characters):

char buff[MAX_SIZE];
char *p = buff;

Or use dynamic memory allocation:

char *p = malloc(INITIAL_SIZE);
size_t current_size = INITIAL_SIZE;
// Later
if (p - initial == current_size) {
  char *buff_new = realloc(initial, current_size * 2);
  if (buff_new) {
    initial = buff_new;
    p = initial + current_size;
    current_size *= 2;
  }
  else
    // should probably abort here, the program is out of memory. Bad bad bad.
}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458