Reputation: 237
Assume I have a struct
struct
foo{
char *p1;
char *p2;
char *p3;
}foo;
and I have assigned the struct malloc - allocated string line that
#include <stdlib.h>
#include <string.h>
char temp[] = "this is string"
char *allocated_temp = malloc(sizeof(temp));
strcpy(allocated_temp, temp);
struct foo bar;
bar.p1 = strtok(allocated_temp, " ");
bar.p2 = strtok(NULL, " ");
bar.p3 = strtok(NULL, " ");
I want to free p1
without freeing the other memory that is pointed to by p2
and p3
. using realloc
will not work as p3
will be freed first, and I am searching for a more of a elegant solution than using coping the struct to a new one without the first part or reallocating the other two strings to a different address.
What good solutions does this problem have?
(to clarify, when I am saying I want to free p1
i mean the "this\0"
part of the string.
Upvotes: 1
Views: 516
Reputation: 6144
There is no solution to your problem with standard tools (malloc
, etc). You can only free the end of the memory that was allocated by realloc()
-ing with a smaller size.
If you want to free p1
this way, you must first move your data to the beginning of the allocated block, update your pointers (p2 and p3) and then call realloc()
.
The best way is probably to change your program in order to malloc p1, p2 and p3 separately.
Upvotes: 1