C语言 复制字符串 malloc


今天在看前辈的代码,对其中字符串复制有时候直接把指针赋给另一个指针,有的malloc一个内存,然后把整个字符串的值拷贝过来,有点费解,就研究了一下,会了之后发现也没什么奥秘,其实很简单,不过还是记录一下比较好。   先写结论:如果要拷贝的源字符串的内存会被回收,那么就必须malloc一个内存再拷贝整个字符串(有时候malloc是防止修改源字符串,不过不考虑这个因素),如果不会被回收则不用。   下面是测试代码

#include <stdio.h>
#include <string.h>

typedef void(*str_cpy_slk)(char *name);
void test(str_cpy_slk cb);
void call_back(char *name);

char *test_name = NULL;
int main(void)
{
  test(call_back);

  printf("name:%s\n", test_name);

  return 0;
}

void test(str_cpy_slk cb)
{
  char myname[8] = {0};
  snprintf(myname, sizeof(myname), "%s", "slk");
  printf("myname:%s\n", myname);
  cb(myname);
}

void call_back(char *name)
{
  test_name = name;
  printf("test_name:%s\n", test_name);
}

  已不可显示。 用malloc开辟内存,再赋值的话,则可以

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

typedef void(*str_cpy_slk)(char *name);
void test(str_cpy_slk cb);
void call_back(char *name);

char *test_name = NULL;
int main(void)
{
  test(call_back);

  printf("name:%s\n", test_name);

  free(test_name);

  return 0;
}

void test(str_cpy_slk cb)
{
  char myname[8] = {0};
  snprintf(myname, sizeof(myname), "%s", "slk");
  printf("myname:%s\n", myname);
  cb(myname);
}

void call_back(char *name)
{
  test_name = (char *)malloc(strlen(name) + 1);
  snprintf(test_name, strlen(name) + 1, "%s", name);
  printf("test_name:%s\n", test_name);
}

本文永久更新链接地址

相关内容