我的最后一个printf语句未打印,我不确定是什么问题,因为我正在使用getchar读取标准输入,因此我也必须使用%s来解决此问题。我试图使最后一个printf语句从标准输入中打印出确切的输入。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define INITIAL_BUFFER_SIZE 16

// Input: pointer to the the old_Buffer i.e. *buffer and the pointer to the old_Buffer size i.e. *buffer_size
// Output: pointer to the new_Buffer i.e. *temp
// Summary: Function to increase the buffer size to double whenever the old_Buffer reaches the max possible size
char* IncreaseBuffer(char *buffer,int *buffer_size){

// Creating a new buffer of double the size
int temp_sz = *buffer_size;
temp_sz = 2*temp_sz;
char *temp;
temp = realloc(buffer, temp_sz);

// If the allocation is not successful, then exit the program and print the error
if (!temp) {
    printf("Error: Unable to Realloc\n");
    exit(EXIT_FAILURE);
}

// Update the buffer size as per the new buffer and return the new buffer instead of the old buffer
*buffer_size = temp_sz;
return temp;
}

int main(void){
// INITIAL BUFFER
char *myString;
myString = malloc(INITIAL_BUFFER_SIZE);
int curr_size = INITIAL_BUFFER_SIZE;

// TEMPORARY CHARACTER TO STORE THE READ CHARACTER
char ch;
printf("Enter a string: ");

// Number of buffer increases
int buff_inc = 0;

// Length of the string
int len = 0;

while((ch=getchar())!=EOF){
    if(ch == '\n'){
        // If character read is a new line, then we break and assume that we have got our string to print by now
        break;
    }else{
        if(len >= curr_size - 1){
            // If length of the string is greater than the buffer size, then we increase the buffer size
            // Also increment the number of buffer increases
            myString = IncreaseBuffer(myString, &curr_size);
            buff_inc++;
        }
        // Append the read character to the end of the buffer
        myString[len++] = ch;
    }
}

printf("String size: %d\n", len);
printf("Buffer increases: %d\n", buff_inc);
printf("You entered: %s\n",myString);

return 0;
}

最佳答案

调用realloc后,一定不能释放旧缓冲区。那很不好。它已经过调整大小,内存分配已处理完毕。重新分配后,它甚至可能保留相同的地址。

只需删除以下几行:

// Free the old buffer
free(buffer);
buffer = NULL;


并且,在注释中已经指出,您忘记了终止字符串。在循环之后执行此操作:

myString[len] = '\0';

10-06 04:09