V
V
Vadim kyklaed2018-05-07 21:53:24
C++ / C#
Vadim kyklaed, 2018-05-07 21:53:24

Dynamic memory allocation for an array, what's wrong?

Hi, I'm redoing an example from a SI book. the task says to determine the longest string entered from the keyboard and display it on the screen. The problem is that apparently somewhere I'm not working correctly with the pointer, it seems to me so. for some reason it does not accept more than 24 characters, the first time it seems to increase memory if the initially allocated one has ended. but when you enter the second line, the redistribution does not work and the program ends. I can't figure out what I did wrong

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
int getline(char *p1,char *p2);
void copy (char *p2,char *p1);

int main(){
  char *p1,*p2;
  int len;
  int max;
  int n =100;
  p1 = (char*)malloc(n * sizeof(char));
  p2 = (char*)malloc(n * sizeof(char));
  
  while((len=getline(p1,p2)) > 0){
    
    if (len>max){
      max=len;
      copy(p2,p1);
    }
  }
  if (max>0){
    int i;
    printf("%s",p2);

  }
  free(p1);
  free(p2);
  return 0;
}

int getline(char *p1,char *p2){
  int c, i;
  for (i=0;  (c=getchar()) != EOF && c != '\n'; ++i){
    if (i==10){
      printf("%s\n","UP1");
      p1 = (char*)realloc(p1, 2 * sizeof(char));
      p2 = (char*)realloc(p2, 2 * sizeof(char));
      printf("%s\n","UP2");	
    }
    printf("c[%d] = %c\n",i,c);
    *(p1+i)=c;
  }
  if (c == '\n'){
    *(p1+i) = c;
    ++i;
  }
  *(p1+i)='\0';
  return i;
}

void copy(char *p2, char *p1){
  int i;
  i=0;
  
  while ((*(p2+i) = *(p1+i)) != '\0'){
    ++i;
  }
  free(p1);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2018-05-07
@kyklaed

1) Realloc takes the size of the expected memory, you just give it 2.
2) After that, you write to some random memory.
3) You pass a single pointer to the function. For this to work and the pointer to change, you must pass a double. That is, after exiting the function, if you had a reallock, your buffer is still garbage.
4) It is not necessary to re-allocate the second buffer each time.
5) there is no need to copy from one buffer to another. It is enough to swap the buffers (swap through the third variable).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question