Uprising
Member
Hi, I am try to allocate memory for two objects at the same time. This is so that I can quickly reference to the second object by pointer arithmetic.
For example
CODE
void *memory = malloc(sizeof(int) + sizeof(char));
int *firstPart;
char *secondPart;
char *pointArith;
firstPart = memory;
pointArith = memory + sizeof(int);
secondPart = pointArith;
*firstPart = 4;
*secondPart = 'L';
printf("firstPart %d, secondPart %c\n",*firstPart,*secondPart); /* Test to see if they have been assigned
correct values (Which it does) */
free(firstPart);
free(secondPart);
When running the debugger it crashes when freeing the secondPart. Is this because free() will try and release memory that is sizeof(int) + sizeof(char) bytes long instead of sizeof(char) bytes?
So I just need to use free once for the firstPart and there will be no memory leak?
For example
CODE
void *memory = malloc(sizeof(int) + sizeof(char));
int *firstPart;
char *secondPart;
char *pointArith;
firstPart = memory;
pointArith = memory + sizeof(int);
secondPart = pointArith;
*firstPart = 4;
*secondPart = 'L';
printf("firstPart %d, secondPart %c\n",*firstPart,*secondPart); /* Test to see if they have been assigned
correct values (Which it does) */
free(firstPart);
free(secondPart);
When running the debugger it crashes when freeing the secondPart. Is this because free() will try and release memory that is sizeof(int) + sizeof(char) bytes long instead of sizeof(char) bytes?
So I just need to use free once for the firstPart and there will be no memory leak?