Hi:
I'm having some issues with using realloc... what I'm doing is resizing a character array so that I can copy a different array into the new one...
Now if the size of the destination array is not at least the size of the source array then we need to allocate more memory for it.
So I did:
realloc(dst->str,sizeof(char) * src_length + 1);
where dst->str is a char array and src_length is the length of the character array in src. When I do this I get a whole slew of errors from valgrind:
invalid write of size 1
invalid read of size 1
and a bunch of memory leak errors.
Is that not how I reallocate an array? When I change the realloc line to:
free(dst->str);
dst->str = malloc(sizeof(char) * src_length) + 1);
Everything works??
4 replies to this topic
#1
Posted 20 March 2011 - 08:42 AM
|
|
|
#2
Posted 20 March 2011 - 09:00 AM
chili5 said:
realloc(dst->str,( sizeof(char) * (src_length+1) );
#3
Posted 20 March 2011 - 09:10 AM
Why did you put that in the parenthesis???
#4
Posted 20 March 2011 - 09:14 AM
Because you want memory for src_length+1 chars.
So, let's say src_length equals 6. You want to allocate 7*sizeof(char) bytes, right? With the parenthesis you do sizeof(char) * (6+1)=sizeof(char)*7. Without, you do sizeof(char)*6, and THEN you add +1.
I hope I was clear enough :D
Anyway, you can avoid sizeof(char) since it is always equal to 1.
So, let's say src_length equals 6. You want to allocate 7*sizeof(char) bytes, right? With the parenthesis you do sizeof(char) * (6+1)=sizeof(char)*7. Without, you do sizeof(char)*6, and THEN you add +1.
I hope I was clear enough :D
Anyway, you can avoid sizeof(char) since it is always equal to 1.
#5
Posted 20 March 2011 - 02:13 PM
The problem is that realloc does not take a char*& it takes a char* and returns another, possibly different char*. Therefore you must do this:
dst->str = realloc(dst->str,src_length + 1);
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









