In this code why do you use malloc here (line 18):Code:struct STRING { int size; char *theString; }; typedef struct STRING String; String * newString( char const * const init ) { String *newString = NULL; newString = (String *)malloc( sizeof( String ) ); if ( NULL != newString ) { newString->theString = (char *)malloc( strlen( init ) + 1 ); if ( NULL != newString->theString ) { strcpy( newString->theString, init ); newString->size = strlen( newString->theString ); } // not enough memory, clean up else { free( newString ); // set ptr to NULL so we don't illegally reference it newString = NULL; } } // don't use a struct declaration... // struct assignment doesn't do deep copying return newString; }
newString->theString = (char *)malloc( strlen( init ) + 1 );
instead of just directly copying the initial string
strcpy(newString -> theString, init);
I was told that when you malloc you put the object onto the heap so that don't disappear after the function ends.
So if you didn't malloc but instead copied directly what would happen?
I tried this and the terminal said: Segmentation fault (core dumped)
I don't get what happened.