c - 获取指针错误引用的 strcpy 和 strcat 的实现

标签 c string strcpy strcat

<分区>

Possible Duplicate:
Any better suggestions for this c functions copyString,concatString

这是一个求职面试的问题,我需要用特定的签名来实现它这是我需要工作的代码:

int main(int argc, char *argv[])
{

    char *str = NULL;
    new_strcpy(&str , "string one");
    new_strcpy(&str , str +7);
    new_strcat(&str , " two");
    new_printf(&str , "%str !", s);
    puts(str ); 
    new_free(&str);
    return 0;
}

这是我对 new_strcpy 的实现:

char* new_strcpy(char **dst,const char *source)
{

  char *ans=*dst;

  while(**dst++=*source++);

  return ans;

}

但是这个解决方案崩溃了,有人可以帮助我吗?

最佳答案

您的解决方案的问题是您未能为 *dst 分配内存。

考虑需要工作的前三行代码:

char *str = NULL;
new_strcpy(&str , "string one");
new_strcpy(&str , str +7);         // ***

由此可见:

  1. new_strcpy() 需要为结果分配内存。
  2. 当重新分配 str 时,new_strcpy() 需要释放之前的 str 以避免内存泄漏。
  3. 要使上面的行 *** 正常工作,释放必须发生在分配之后

这是一个框架实现,可以为您提供思路。我根据 strcpy() 等实现函数,但如果调用库函数是不允许的,您可以编写自己的循环(您已经知道该怎么做)。

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

void new_strcpy(char** dst, const char* src) {
    char* orig_dst = *dst;
    *dst = malloc(strlen(src) + 1);
    strcpy(*dst, src); /* replace with a loop if calling strcpy() is not permissible */
    free(orig_dst);
}

void new_strcat(char** dst, const char* src) {
    char* orig_dst = *dst;
    *dst = malloc(strlen(*dst) + strlen(src) + 1);
    strcpy(*dst, orig_dst); /* replace with a loop if calling strcpy() is not permissible */
    strcat(*dst, src);      /* ditto for strcat() */
    free(orig_dst);
}

void new_free(char** dst) {
    free(*dst);
    *dst = NULL;
}

int main(int argc, char *argv[])
{
    char *str = NULL;
    new_strcpy(&str , "string one");
    new_strcpy(&str , str +7);
    new_strcat(&str , " two");
/*    new_printf(&str , "%str !", s); */
    puts(str );
    new_free(&str);
    return 0;
}

我将实现 new_printf() 作为读者的练习。 :-)

关于c - 获取指针错误引用的 strcpy 和 strcat 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13719663/

相关文章:

c# - 我如何从字符串中剥离 Html 并设置字符限制?

c++ - C++中getline的段错误

c - 'strcpy' 与 'malloc' ?

C 字符串在一个函数中是正确的,在另一个函数中转储垃圾

c - AVR : Relocation truncated to fit

c++ - 停止使用 libpcap 捕获数据并将其保存在文件中

c++ - 弹性和 Bison : string literal

c - 为什么我的 strcpy() 不覆盖整个字符串并保留最后一个 char [] 中的字符?

c - 共享内存中带有 strcpy 的 BAD_ACCESS (C)

c - 从 UART 读取数据时停止程序