Crul
07-11-2008, 08: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
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