Reputation: 39
I have a problem with below function.
When I try to realloc()
memory I get more than I actually asked for!
In this instance I try to concatenate 2 strings, one who is 14 characters long and one who is 11 characters long, but the end result is that memTemp
is 38 characters long even though memNewSize
shows that it is in fact 25, does anyone know what to do?
int dstring_concatenate(DString* destination, DString source)
{
assert(destination != NULL); // Precondition: destination ar ej NULL
assert(*destination != NULL); // Precondition: *destination ar ej NULL
assert(source != NULL); // Precondition: source ar ej NULL
//Dstring looks like this = "typedef char* Dstring;"
int memNewSize = strlen(*destination) + strlen(source);
char *memTemp;
memTemp = (char*)realloc(memTemp, sizeof(char) * memNewSize);
printf("%d\n", memNewSize);
printf("%d\n", strlen(memTemp));
if(memTemp == NULL)
{
printf("Could not allocate new memory.\n");
return 0;
}
else
{
*destination = memTemp;
strcat(*destination, source);
return 1;
}
}
Upvotes: 0
Views: 467
Reputation: 39
Alright, I got it to work, thanks so much guys! Updated code below.
int dstring_concatenate(DString* destination, DString source)
{
assert(destination != NULL); // Precondition: destination ar ej NULL
assert(*destination != NULL); // Precondition: *destination ar ej NULL
assert(source != NULL); // Precondition: source ar ej NULL
// Dstring look like this = "typedef char* Dstring;"
int memNewSize = strlen(*destination) + strlen(source);
char *memTemp;
memTemp = (char*)realloc(*destination, sizeof(char) * memNewSize+1);
if(memTemp == NULL)
{
printf("Could not allocate new memory.\n");
return 0;
}
else
{
*destination = memTemp;
strcat(*destination, source);
return 1;
}
}
Upvotes: 0
Reputation: 134386
The problem here is, realloc()
works (properly) on only
NULL
pointers.Quoting C11
, chapter §7.22.3.5
If
ptr
is a null pointer, therealloc
function behaves like themalloc
function for the specifiedsize
. Otherwise, ifptr
does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to thefree
orrealloc
function, the behavior is undefined. [....]
In your case, memTemp
(being an automatic storage local scoped variable) is just an unitialized pointer, with an indeterminate value, pointing to who knows what address! It's not even guaranteed to be NULL
. So, all you have is undefined behavior.
Just a guess: Probably you meant to initialize memTemp
with incoming *destination
?
That said, as pointed out in comments under the actual question,
realloc()
should be memNewSize + 1
to be able to hold the null-terminator.sizeof(char)
is guaranteed to be 1
in C, so using it as a multiplier is redundant.Upvotes: 6