Search code examples
arrayscdynamic-memory-allocation

copy a string of characters in an other string using dynamic memory alocation but it doesn t works


I'm trying to copy a string of characters in another string using dynamic memory allocation but it doesn't work:

#include <stdlib.h>
#include <stdio.h>
int main() {
    char* s1, * s2, * s3;
    s1 = (char*)malloc(11 * sizeof(char));
    s2 = (char*)malloc(11 * sizeof(char));
    s3 = (char*)malloc(11 * sizeof(char));
    fgets(s1, 11, stdin);
    fgets(s2, 11, stdin);
    int i = 0;
    do {
        *(s3 + i) = *(s1 + i);
        i++;
    } while (*(s1 + i) != '\n' && *(s1 + i) != '\0');
    puts(s3);
    return 0;
}

Solution

  • You do not null terminate the s3 string.

        } while (*(s1 + i) != '\n' && *(s1 + i) != '\0');
        s3[i] = 0;
        puts(s3);