Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //-std=c99 -Wall -Wextra -Wpedantic -Wshadow
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdint.h>
- int main ()
- {
- int32_t blk_1[]={100,101,102,103,104,105,106,107,108};
- int32_t blk_2[]={200,201};
- int32_t blk_3[]={300,301,302,303,304,305,306,307,308,309,310,311,312,313,314};
- uint32_t blkNumE_1 = sizeof(blk_1)/sizeof(blk_1[0]);
- uint32_t blkNumE_2 = sizeof(blk_2)/sizeof(blk_2[0]);
- printf("info: blkNumE_1: %d\n", blkNumE_1);
- printf("info: blkNumE_2: %d\n", blkNumE_2);
- int32_t *p1;
- int32_t *p2;
- int32_t *p3;
- int32_t *buffer;
- int32_t *bufferTmp;
- uint32_t buffSize;
- //in bytes
- buffSize = sizeof(blk_1) + sizeof(blk_2);
- printf("info: buffer size: %d bytes\n", buffSize);
- buffer = malloc(buffSize);
- if(!buffer)
- {
- printf("error: memory allocation (1)\n");
- return 1;
- }
- memcpy(buffer, blk_1, sizeof(blk_1));
- /*
- buffer + blkNumE_1; because buffer is int32_t*;
- buffer + N; in bytes adds number * sizeof(int32_t) to the address of the buffer
- */
- memcpy(buffer + blkNumE_1, blk_2, sizeof(blk_2));
- p1 = buffer;
- p2 = buffer + blkNumE_1;
- printf("info: p1[0]: %d\n", p1[0]);
- printf("info: p2[0]: %d\n", p2[0]);
- buffSize += sizeof(blk_3);
- printf("info: buffer size: %d bytes\n", buffSize);
- bufferTmp = realloc(buffer,buffSize);
- if(!bufferTmp)
- {
- printf("error: memory allocation (2)\n");
- free(buffer);
- return 1;
- }
- buffer = bufferTmp;
- memcpy(buffer + blkNumE_1 + blkNumE_2, blk_3, sizeof(blk_3));
- p1 = buffer;
- p2 = buffer + blkNumE_1;
- p3 = buffer + blkNumE_1 + blkNumE_2;
- printf("info: p1[0]: %d\n", p1[0]);
- printf("info: p2[0]: %d\n", p2[0]);
- printf("info: p3[0]: %d\n", p3[0]);
- //memmove(p2, p3, sizeof(blk_3));
- memmove(buffer + blkNumE_1, buffer + blkNumE_1 + blkNumE_2, sizeof(blk_3));
- buffSize -= sizeof(blk_2);
- printf("info: buffer size: %d bytes\n", buffSize);
- //shrink the allocated memory
- bufferTmp = realloc(buffer,buffSize);
- if(!bufferTmp)
- {
- printf("error: memory allocation (3)\n");
- free(buffer);
- return 1;
- }
- buffer = bufferTmp;
- p1 = buffer;
- p2 = buffer + blkNumE_1;
- printf("info: p1[0]: %d\n", p1[0]);
- printf("info: p2[0]: %d\n", p2[0]);
- printf("info: p2[2]: %d\n", p2[2]);
- free(buffer);
- return 0;
- }
- /*
- output:
- info: blkNumE_1: 9
- info: blkNumE_2: 2
- info: buffer size: 44 bytes
- info: p1[0]: 100
- info: p2[0]: 200
- info: buffer size: 104 bytes
- info: p1[0]: 100
- info: p2[0]: 200
- info: p3[0]: 300
- info: buffer size: 96 bytes
- info: p1[0]: 100
- info: p2[0]: 300
- info: p2[2]: 302
- valgrind:
- HEAP SUMMARY:
- in use at exit: 0 bytes in 0 blocks
- total heap usage: 4 allocs, 4 frees, 1,268 bytes allocated
- All heap blocks were freed -- no leaks are possible
- ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
- */
Add Comment
Please, Sign In to add comment