简体   繁体   中英

Read input and put it to a char pointer

I make a test case about putting input to a char pointer. When I try to run this program, the output isn't right(it becomes a series of random characters like : _ @$).I intend to print each element in that char pointer. I make some changes on my code, but it's still wrong(same problem as before). Could someone help me to figure out what's going wrong and the way to fix it?

int chara;
int counts =0;

main(){

    char *buffer=(char *)malloc(sizeof(char)*25);
    while((chara=getchar())!= EOF&& counts<25){
        *buffer++ = chara;
        printf("%c\n",*buffer);
        counts++;

    }
    *buffer = '\0';
     printf("%s\n",buffer);
     free(buffer);
}

Modify your code.

    int chara; //getchar() returns int
    int i=0;
    char *buffer=malloc(20); //allocate correctly
    while(  ( (chara=getchar())!= EOF) && ( i!=19 ) ) { //check against EOF and check counter value to avoid input with legth greater than allocated size.
        buffer[i]= chara;   
        //use indexing with counter variable to avoid errors with free()
        // if change pointer you can't free() memory  
         printf("%c\n",buffer[i++]);
    }

    buffer[i] = '\0';
     printf("%s\n",buffer);
     free(buffer);

Since you increase the value of buffer in the loop, the code after the loop is wrong. You can't free() the incremented buffer , that will point at an address which hasn't been returned by malloc() .

Basically you're doing:

char *buffer = malloc(25);
...
free(buffer + length of string the user entered);

Which means that the address you pass to free() is no longer the same that was returned by malloc() , which is an error.

Your other problem is that this:

    *buffer++ = chara;
    printf("%c\n",*buffer);

prints out garbage -- you assign chara to where buffer is pointing, increment buffer , and then print out the (uninitialized) location that buffer now points to.

Just print chara instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM