简体   繁体   English

strcat两个字符指针时如何修复段错误

[英]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).每个都为dns_namedns_name2分配一个固定长度的字符数组,每个字符长度为两个字符(一个用于点,一个用于nul终止符)。

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:要解决此问题,您需要将字符串声明为更长的 arrays,能够保持strcat调用结果的最大预期长度:

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:此外,在您的 output 行中,您不应取消引用字符串指针,因此: 而不是:

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:编辑:如果您需要dns_namedns_name2作为实际指针,那么您可以创建字符 arrays 作为单独的变量并将您的指向它们:

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.它使用 dns_buffer 和 dns_buffer2 创建动态分配的字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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