Memory reallocation


/ Published in: C
Save to your folder(s)

Realloc memory at every X steps. Useful when allocating fixed number of items (in this case chars).


Copy this code and paste it in your HTML
  1. char *variable;
  2. int size = 120, tmpsize = 0;
  3.  
  4. variable = (char *)malloc(size*sizeof(char));
  5.  
  6. while ( ... ) {
  7. //Realloc memory
  8. tmpsize += 40;
  9. if (tmpsize > size) {
  10. size += 120;
  11. variable = (char *)realloc(variable, size*sizeof(char));
  12. }
  13.  
  14. strcat(variable,"your string to add with a fixed size");
  15. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.