fork download
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <stdbool.h>
  7. //#include <crtdbg.h>//VC only...
  8.  
  9. typedef struct Memory{
  10. void* Memory;
  11. size_t Length;
  12. size_t ESize;
  13. }Memory;
  14.  
  15. Memory ConstructMemory(size_t Length, size_t ElementSize){
  16. Memory M={ 0, };
  17.  
  18. M.Memory = calloc(Length, ElementSize);
  19. if (M.Memory == NULL) return M;
  20.  
  21. M.Length = Length;
  22. M.ESize = ElementSize;
  23.  
  24. return M;
  25. }
  26.  
  27. bool ResizeMemroy(Memory* M, size_t Length){
  28. void *T = NULL;
  29.  
  30. T= realloc(M->Memory, Length*M->ESize);
  31. if (errno == ENOMEM) return false;
  32. if (T != NULL && T != M->Memory)M->Memory = T;
  33. M->Length = Length;
  34.  
  35. return true;
  36. }
  37.  
  38.  
  39. bool AppendMemory(Memory* M, size_t Add){
  40. return ResizeMemroy(M, M->Length + Add);
  41. }
  42.  
  43. bool IsMemoryNull(Memory* M){
  44. return M->Memory == NULL;
  45. }
  46.  
  47.  
  48. void DestructMemroy(Memory* M){
  49. free(M->Memory);
  50. M->Memory = NULL;
  51. M->Length = 0;
  52. M->ESize = 0;
  53. }
  54.  
  55. bool AppendString(Memory* M, char* str){
  56. if (AppendMemory(M, strlen(str)) == false) {
  57. DestructMemroy(M);
  58. exit(1);
  59. }
  60. strcat(M->Memory, str);
  61.  
  62. return true;
  63. }
  64.  
  65.  
  66. int main(){
  67. char F[] = "I";
  68. char Mi[] = " am";
  69. char L[] = " Bob.";
  70.  
  71. Memory M = ConstructMemory(1, sizeof(char));
  72. if (IsMemoryNull(&M) == true) exit(1);
  73.  
  74. AppendString(&M, F);
  75.  
  76. printf("Memory is '%s'\n", M.Memory);
  77.  
  78. AppendString(&M, Mi);
  79.  
  80. printf("Memory is '%s'\n", M.Memory);
  81. AppendString(&M, L);
  82.  
  83. printf("Memory is '%s'\n", M.Memory);
  84. AppendString(&M, "We");
  85.  
  86. printf("Memory is '%s'\n", M.Memory);
  87. AppendString(&M, " are");
  88.  
  89. printf("Memory is '%s'\n", M.Memory);
  90. AppendString(&M, " Bob.");
  91.  
  92. printf("Memory is '%s'\n", M.Memory);
  93. DestructMemroy(&M);
  94.  
  95. printf("Done!\n");
  96.  
  97. //_CrtCheckMemory();//vc only...
  98. return 0;
  99.  
  100. }
  101.  
  102.  
Success #stdin #stdout 0s 2140KB
stdin
Standard input is empty
stdout
Memory is 'I'
Memory is 'I am'
Memory is 'I am Bob.'
Memory is 'I am Bob.We'
Memory is 'I am Bob.We are'
Memory is 'I am Bob.We are Bob.'
Done!