2016-02-16 2 views
-2

моя последняя инструкция printf не печатается. Я не уверен, что случилось, так как я использую getchar для чтения стандартного ввода, я также должен использовать% s для этой проблемы. Я пытаюсь сделать последнее заявление printf напечатать точный ввод со стандартного ввода.printf statement error

#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; 
} 
+0

Вам нужно NULL ('\ 0') завершить строку. –

+0

Благодарю вас за помощь. однако, я все еще не печатаю последнюю инструкцию printf, которую вы ввели: – AWWU

+0

@UmamaheshP: 'NULL' является константой * указателя нуль *. '' \ 0'' является нулевым символом. –

ответ

2

Вы не должны бесплатно старый буфер после вызова realloc. Это плохо. Он уже был изменен и распределено по памяти. Он может даже сохранить один и тот же адрес после перераспределения.

Просто удалите следующие строки:

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

И уже отмечалось в комментариях, что вы забыли прекратить вашу строку. Делайте это после цикла:

myString[len] = '\0'; 
0

стрижки вниз после того, как только вижу ответ @ Пэдди, но для записи это от realloc Документов

В случае успеха возвращает указатель на начало вновь выделенной памяти. Возвращаемый указатель должен быть освобожден с помощью free() или realloc(). Исходный указатель ptr недействителен, и любой доступ к нему - это неопределенное поведение (даже если перераспределение было на месте).

При сбое возвращает нулевой указатель. Исходный указатель ptr остается действительным и может потребоваться освободить с помощью free() или realloc().

+0

Благодарим вас за разъяснение, очень ценим! – AWWU