用C连接字符串的安全方法是什么? [英] What is a safe way to join strings in C?

查看:203
本文介绍了用C连接字符串的安全方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从两个字符串构建一个文件路径.我可以使用它(不过未经测试):

I need to construct a path to a file from two strings. I could use this (not tested, though):

/* DON'T USE THIS CODE! */
/* cmp means component */
char *path_cmp1 = "/Users/john/";
char *path_cmp2 = "foo/bar.txt";
unsigned len = strlen(path_cmp1);
char *path = path_cmp1;
for (int i = 0; i < strlen(path_cmp2); i++) {
  path[len + i] = path_cmp2[i];
}

但是我猜这可能导致内存损坏.有没有更好的方法可以做到这一点,或者在标准库中有此功能?

but this could lead to memory corruption I guess. Is there a better way to do this, or is there a function for this in the standard library?

推荐答案

#include <stdlib.h>
#include <string.h>

char *join(const char* s1, const char* s2)
{
    char* result = malloc(strlen(s1) + strlen(s2) + 1);

    if (result) // thanks @pmg
    {
        strcpy(result, s1);
        strcat(result, s2);
    }

    return result;
}

这很简单,可以就地编写,尤其是当您有多个字符串要串联时.

This is simple enough to be written in place, especially when you have multiple strings to concatenate.

请注意,这些函数返回其目标参数,因此您可以编写

Note that these functions return their destination argument, so you can write

char* result = malloc(strlen(s1) + strlen(s2) + 1);
assert(result);
strcat(strcpy(result, s1), s2);

但这可读性较差.

这篇关于用C连接字符串的安全方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆