Jump to content

realloc issues

- - - - -

  • Please log in to reply
4 replies to this topic

#1
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
  • Programming Language:Java, C#, PHP
  • Learning:C, C++, C#, PHP, Transact-SQL, Assembly, Scheme
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??

#2
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts

chili5 said:

realloc(dst->str,( sizeof(char) * (src_length+1) );
fixed

#3
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
  • Programming Language:Java, C#, PHP
  • Learning:C, C++, C#, PHP, Transact-SQL, Assembly, Scheme
Why did you put that in the parenthesis???

#4
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
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.

#5
rocketboy9000

rocketboy9000

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
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