Search code examples
csegmentation-faultstrcat

How to fix seg fault when strcat two char pointers


I get a segmentation fault because of my code with pointers. (Pointers are there needed.)

int main()
{    
    char *dns_name = ".";
    char *dns_name2 = ".";
    printf("HELLO\n");
    strcat(dns_name2,dns_name);
    printf("result: %s", *dns_name2);

    return 0;
}

Solution

  • You may give that a try. It uses dns_buffer and dns_buffer2 to create a dynamically allocated string.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void) {
        char *dns_name = "hh";
        char *dns_name2 = "hhha";
        char *total_dns = malloc(strlen(dns_name) + strlen(dns_name2) + 1);
        printf("HELLO\n");
        strcpy(total_dns, dns_name);
        strcat(total_dns,dns_name2);
        printf("result: %s", total_dns);
    
        free(total_dns);
        return 0;
    }