Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Nov 2007
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Using malloc to dynamically increase the size of an array in C

    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

  • #2
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by Crul View Post
    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

  • #3
    New to the CF scene
    Join Date
    Nov 2007
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks for the help, I figured it out

  • #4
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by Crul View Post
    Thanks for the help, I figured it out
    you are welcome,

    regards

  • #5
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    Or you can use realloc and then you don't need to worry about copying the data.
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •