user1991562
user1991562

Reputation: 285

Dynamic memory allocation in C using realloc

I have read the other SO question about using realloc to get a new pointer to the beginning of a bigger memory address space but I cant figure out what I am doing wrong. It prints a backtrace and memory dump. I later try to access strhldr but I dont think it even gets that far.

char *strhldr = (char *)malloc(strsize);

 int chrctr = 0;
 if(chrctr == strsize - 3){ // when you get close
  strsize = strsize*2; //double size
  char *temp = realloc(strhldr, strsize); //make more room
    if(temp == NULL)
     printf("reallocate failed\n");
    else{
     strhldr = temp;
     free(temp); // removed same issue
    }
} 

// Later attempt to add it to an array
cmdargs[i] =  strhldr;

This is all within a while loop where chrctr and strsize get incremented

complete code

  int argctr = 64;
  char **cmdargs = (char **) malloc(argctr * sizeof(char*));
  char c = getchar();
  int i = 0;


  while(c != '\n' && c != EOF){ //read through a String of stdin
  int strsize = 32;
  char *strhldr = (char *)malloc(strsize);
  char *strstarthldr = strhldr;


    if(c == ' ')
      c = getchar();
    while(c != ' ' && c != '\n' && c != EOF){

      int chrctr = 0;
     if(chrctr == strsize - 3){ // when you get close
      strsize = strsize*2; //double size
      char *temp = realloc(strhldr, strsize); //make more room
        if(temp == NULL)
         printf("reallocate failed\n");
        else
         strhldr = temp;

    }      //add that word to the array of strings
      strhldr[chrctr] = c;
      chrctr++;
      c = getchar();

    }
    strhldr[charctr] = '\0';
    //strhldr = strstarthldr;
    cmdargs[i] =  strhldr;
    i++;
  }

Upvotes: 1

Views: 653

Answers (3)

DrC
DrC

Reputation: 7698

Second problem - your value charctr (not chrctr) is not set. Here is a version of your loop. I haven't tested it but it should be close.

  if(c == ' ') {
      c = getchar();
  }

  int chrctr = 0;
  while(c != ' ' && c != '\n' && c != EOF){
     if(chrctr == strsize - 3){ // when you get close
        strsize = strsize*2; //double size
        char *temp = realloc(strhldr, strsize); //make more room
        if(temp == NULL) {
           printf("reallocate failed\n");
           break;
        }
        else {
           strhldr = temp;
        }
     } 
     strhldr[chrctr] = c;
     chrctr++;
     c = getchar();
  }
  strhldr[chrctr] = 0;

Upvotes: 0

n3rd4n1
n3rd4n1

Reputation: 371

It's not very clear to me what you are trying to do but I believe free(temp); invalidates strhldr and future read/write access to it will cause you trouble.

Upvotes: 1

DrC
DrC

Reputation: 7698

On success, realloc will free its argument if needed. So remove the call to free(temp).

Upvotes: 4

Related Questions