This is my task from school: Write a function insertString that inserts the string s2 into s1 at index n.s1 has been allocated using malloc and should be resized (the function is void again).
The program gave me a NULL on PC and when I switched to the phone the compilor said my realloc has a invalid pointer. But I really don't know what I did wrong.
Here is the code:
void insertString(char *str1, char *str2, int n){
int lengStr2=strlen(str2);
printf("%d %d ", lengStr2,n);
printf("\nstr1= %s, str2: %s, n: %d ",str1,str2,n);
str1=(char*)realloc(str1,lengStr2+n+1);
if (str1==NULL){
printf("Error\n");
free(str1);
return -1;
}
printf("\nstr1= %s, str2: %s, n: %d ",str1,str2,n);
memcpy(str1+n,str2,lengStr2+1);
printf("\nstr1= %s, str2: %s, n: %d ",str1,str2,n);
}
void testInsertString( char *str2, int n, char *expect){
char*str1=(char*)malloc(3*sizeof(char));
str1="hoi";
printf("\nstr1= %s, str2: %s, n: %d ",str1,str2,n);
insertString(str1,str2,n);
printf("--> result:%s --> ",str1);
(strcmp(str1,expect)==0)?printf("Success"): printf("Failure");
free(str1);
printf("\nIs Free\n");
}
Here the output:
str1= hoi, str2: Hallo, n: 1 5 1
str1= hoi, str2: Hallo, n: 1 Error
--> result:hoi --> Failure
Is Free
Process returned 0 (0x0)
Please if you know what I did wrong can you show me the correct version? Even so I have the problem that I can't right a program right just by reading a text, I need to see how it should be written. So I need to see the right result to learn from the mistake ^^" (that's why some stuff in school is for me really hard). Thanks in advance ^^
str1is a string literal. It cannot be realloced. Afterstr1=malloc(...), you need to copy data intostr1withsprintforstrcator the like. Reassigningstr1="hoi"throws away the address of the memory you allocated. It is a memory leak.-Wwrite-stringsto compiler flags; that would cause it to warn aboutstr1="hoi".int lengStr2=strlen(str2);the function:strlen()returns asize_t(an unsigned value) not anintvoid insertString(char *str1, char *str2, int n){this function is declared (via thevoid) to not return a value, However, that function contains:return -1;When compiling, always enable the warnings, then fix those warnings. ( forgcc, at a minimum use:-Wall -Wextra -Wconversion -pedantic -std=gnu11) Note: other compilers use different options to produce the same resultsstr1=(char*)realloc(str1,lengStr2+n+1); if (str1==NULL){ printf("Error\n"); free(str1); return -1;1) when calling:realloc()always assign to a 'temp' variable. Otherwise, when the function fails, the original pointer is lost (resulting in a memory leak) 2) error messages should be output tostderr, notstdoutSuggest using:perror( "realloc failed" );3) the returned type isvoid*which can be assigned to any pointer. Casting just clutters the code (and is error prone)