简体   繁体   中英

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;
}

The problem in your code is that the lines:

char *dns_name = ".";
char *dns_name2 = ".";

each allocate a fixed length array of characters to dns_name and dns_name2 , each being two characters long (one for the dot and one for the nul terminator).

To fix the problem, you need to declare the strings as longer arrays, capable of holding the maximum expected length of the result of the strcat call:

char dns_name[50] = "."; // Change 50 to the maximum allowable length.
char dns_name[50] = ".";

Also, in your output line, you shouldn't dereference the string pointer, So: instead of:

printf("result: %s", *dns_name2);

use:

printf("result: %s", dns_name2); // the %s format expects a pointer or array.

Hope this helps. Feel free to ask for further clarification and/or explanation.

EDIT: If you need dns_name and dns_name2 to be actual pointers, then you can create the character arrays as separate variables and point yours to them:

char dns_buffer[50] = ".";
char dns_buffer2[50] = ".";
char *dns_name = dns_buffer;
char *dns_name2 = dns_buffer2;

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM