C the practice (DMA)

动态分配复制字符串:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning (disable:4996)

char* strdup(char const* string) {
    char* new_string;
    new_string = malloc(strlen(string)+1); ///要给字符串末尾的NUL字节留出位置
    if (new_string != NULL) ///一定要判断是否成功分配内存!
        strcpy(new_string, string);
    return new_string;
}

int main() {
    char* str = "hello,world.";
    printf("%s",strdup(str));
    return 0;
}
原文地址:https://www.cnblogs.com/porest/p/14104939.html