-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.

1
  • 6
    p is a pointer to an unallocated memory space . Commented Jan 11, 2017 at 11:17

1 Answer 1

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.
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.