...

View Full Version : Using malloc to dynamically increase the size of an array in C



Crul
07-11-2008, 07:14 PM
Hi all,

I'm having some trouble with malloc. The following is what I'm trying to do.

I have a char pointer s that points to a string str = "Hello". I want to insert the letter i after h and before e (so make it Hiello). So to do this I use malloc on s to expand its size by 1

s = malloc(lengthOfS + 1);

Then I would shift everything starting at e 1 index to the right and insert the letter i right after H.

Now my problem is that when I do malloc the string gets filled with some gibberish characters. I know this because I printed the contents of the string before doing malloc and once again after doing malloc. What I got was...

before malloc ---> Hello

before malloc ---> IIIIIIyyyyy<<<<<<<<<<_i_i

Isn't malloc suppose to just change the size of your string but not corrupt its data?

Any suggestions/comments/help as to how I can fix this would be appreciated.

Thanks

oesxyl
07-11-2008, 07:24 PM
before malloc ---> Hello

before malloc ---> IIIIIIyyyyy<<<<<<<<<<_i_i

Isn't malloc suppose to just change the size of your string but not corrupt its data?

allocate memory and copy data from old data structure to new data structure are different things.
malloc do only allocation, and you must use 'free' to deallocate the old data after you copy the content.

regards

Crul
07-11-2008, 08:02 PM
Thanks for the help, I figured it out

oesxyl
07-11-2008, 08:06 PM
Thanks for the help, I figured it out
you are welcome, :)

regards

oracleguy
07-11-2008, 09:13 PM
Or you can use realloc (http://www.cplusplus.com/reference/clibrary/cstdlib/realloc.html) and then you don't need to worry about copying the data.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum