简体   繁体   中英

Multiple error messages while working with pointer and malloc in c

I'm still very new to C and get multiple error messages in my code and it would be nice if someone could explain these error messages to me.

My code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  char newINPUT;

  char* INPUT = (char*)malloc(1 * sizeof(char));



  while((INPUT = getchar()) =! EOF)
    char* newINPUT = (char*)realloc(INPUT, 2* sizeof(INPUT));
    if(newINPUT =! NULL)
    {
      INPUT = newINPUT;
    }
    else
    {
      free(INPUT);
      printf("Out of memory!");
    }

    return 0;

}

What this shall do is: It should allocate some memory and read what you type. When there is no allocated memory left it should reallocate double as much memory as has been alocated before.

Error messages: warning line 13(that line with while): assignement makes pointer from integer without cast (enabled as default) error line13: lvalue required as left operand of assignement error line14: expected expression before 'char' warning line 17: same as line 13.

Would be nice if someone could explain that to me. Thanks!


EDIT: Thanks for all the answers so far! They truly helped me in understanding malloc und realloc. I've tried another own version yesterday, but I'm not sure if the allocated memory works right since I can't test it with an input large enough. Would that work (syntaxwise) with the realloc and the doubling?

    #include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{

  int *READ; //input
  READ = malloc(sizeof(int));


  while ((*READ = getchar()) != EOF)
  {
    if (READ) //if read not null so memory is enough
    {
      putchar(*READ);
    }
    else
    {
      int x;
      int* extendedREAD = realloc(READ, (x*2));//expression for "double as much as before"????

      if (extendedREAD = NULL) // looking if there s enough memory
      {
        printf("Error, not enough memory!");
      }
      x = x * 2;
    }
  }



  return 0;
}




/*
Zeichen einlesen - checken ob eof, wenn nein, dann speicher ausreichend? nein dann vergräßern, sonst zeichen dazuschreiben, dann wieder vonvorne)
*/

Thank you!

Lots of issues here...

int main()
{
  char newINPUT;

  char* INPUT = (char*)malloc(1 * sizeof(char));

Don't cast the result of a call to malloc() ; it's unnecessary and can cause unexpected problems.

  while((INPUT = getchar()) =! EOF)

Two problems here. First, a =! b a =! b means "set a to the logical complement of b " . You probably wanted to use something of the form a != b ( " a not equal to b " ). Second, getchar() returns an int value. If you try to store the return value in a char container, you may find that it will never be equal to EOF .

    char* newINPUT = (char*)realloc(INPUT, 2* sizeof(INPUT));

Here you are redeclaring newINPUT as a char* pointer. You declared it as char newINPUT earlier on. This will cause a compilation error.

    if(newINPUT =! NULL)

You are setting newINPUT to the logical complement of NULL here. I think you meant if (newINPUT != NULL) . You could have simply used if (newINPUT) instead.

(Nonsense about memory leak deleted — my mistake!)

Overall, your program logic is flawed because you are attempting to double the allocated memory for every single character of input. So even if you fixed the above problems, you would run out of memory after inputting about 32 characters.


Suggested rewrite:

The following code stores the current size of the input buffer in size , and the length of the input string in nchars . Both are initialised to zero. The buffer location itself ( char *input ) can be initialised to NULL , because a call to realloc() with a null pointer is equivalent to calling malloc() . That means we can eliminate one system call from the code.

#include <stdio.h>
#include <stdlib.h>

int main() {
  char *input=NULL, *new_input;
  int c, size=0, nchars=0;

  while (1) {
    if (size==nchars) {
      size = size*2 + (size==0);  /* (size==0) is 1 if size==0, zero othewise */
      if (!(new_input = realloc(input,size))) {
        puts("Out of memory");
        free(input);
        return 1;
      }
      input = new_input;
      printf("Buffer reallocated; new size is %d byte(s)\n",size);
    }
    if ((c=getchar())==EOF) {
      input[nchars] = '\0';  /* Terminate the input string */
      break;
    }
    input[nchars++] = c;
  }

  printf("Buffer size:   %d\n"
         "String length: %d\n"
         "Input was:     %s\n",size,nchars,input);
  free(input);
  return 0;
}

An example of a modification

#include <stdio.h>
#include <stdlib.h>

int main(void){
    int ch;
    char* INPUT = (char*)malloc(1 * sizeof(char));
    int input_buf_size = 1;
    int input_count = 0;

    while((ch = getchar()) != EOF){
        INPUT[input_count] = ch;
        input_count += 1;
        if(input_count == input_buf_size){
            char *newINPUT = (char*)realloc(INPUT, input_buf_size *= 2);
            if(newINPUT != NULL){
                INPUT = newINPUT;
            } else {
                free(INPUT);
                printf("Out of memory!");
                exit(EXIT_FAILURE);
            }
        }
    }
    INPUT[input_count] = '\0';
    puts(INPUT);
    free(INPUT);
    return 0;
}

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