Reputation: 301
I have:
char *data = malloc(file_size+1);
I also have strings such as char *string = "string1"
.
I want to be able to realloc memory to data whenever I'm about to add another string to data. What would be the best way to do this in C, I've seen other ways such as using file_size * 2, however, this would be a waste of memory, what is the best way to do this when adding the length of a string to the memory. This is for a simple desktop application.
Upvotes: 0
Views: 503
Reputation: 9680
You can use realloc
to allocate more memory to an existing dynamically allocated buffer. Also, your pointers to string literals should be const
qualified because they are read-only.
const char *string = "string1"
char *data = malloc(strlen(string) + 1); // +1 for the null byte
strcpy(data, string)
const char *string2 = "hello";
char *temp = NULL;
// +1 for the terminating null byte
int newsize = strlen(data) + strlen(string2) + 1;
// realloc returns NULL in case it fails to reallocate memory.
// save the value of data in temp before calling reallocate
temp = data;
data = realloc(data, newsize);
// check for failure of realloc
if(data == NULL) {
printf("realloc failed\n");
data = temp;
// handle it
}
Upvotes: 0
Reputation: 399949
It's very much up to what you want to optimize for, and that's hard to answer here since you don't say much about what "best" means for you, i.e. what the constraints are.
For a general-purpose program running on a desktop or server machine, I'd over-allocate a lot from the beginning, to avoid having to call realloc()
, and typically double the allocation each time it overflows. The memory will probably not be used (physically) until needed anyway, so why try to "save" it?
If the allocation is going to be long-lived (days or weeks) it might make sense to try to be more conservative. If the number of concatenations is small, it might not. And so on.
Upvotes: 2