C語言中的神獸strdup


  C語言的確博大精深,在C語言的世界中遨游了那么多年,發現自己仍是菜鳥一枚,很多利器沒有能夠駕馭,今天介紹一個神獸,威力無比,但是卻很少人能用得好。

函數原型:

#include <string.h>
char *strdup(const char *s); 

函數介紹:

  strdup()函數是c語言中常用的一種字符串拷貝庫函數,一般和free()函數成對出現。

strdup()在內部調用了malloc()為變量分配內存,不需要使用返回的字符串時,需要用free()釋放相應的內存空間,否則會造成內存泄漏。該函數的返回值是返回一個指針,指向為復制字符串分配的空間;如果分配空間失敗,則返回NULL值。

函數實現:

char * __strdup(const char *s)
{
   size_t  len = strlen(s) +1;
   void *new = malloc(len);
   if (new == NULL)
      return NULL;
   return (char *)memecpy(new,s,len);
}

函數實戰:

#include <syslib.h>
#include<string.h>
int main(void)
{
     char *src =”This is the strdup test”;
     char *dest;
     dest = strdup(s);
     printf(“the dest %s\n”,dest);
 
     return 0;

}

   運行結果是:

the dest This is the strdup test

常用方法:

#include <stdio.h>

#include <string.h>

#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <getopt.h>


static struct option main_options[] = {
        { "help",       0, 0, 'h' },
        { "verbose",    0, 0, 'v' },
        { "msbc",       0, 0, 'm' },
        { "subbands",   1, 0, 's' },
        { "bitpool",    1, 0, 'b' },
        { "joint",      0, 0, 'j' },
        { "dualchannel",0, 0, 'd' },
        { "snr",        0, 0, 'S' },
        { "blocks",     1, 0, 'B' },
        { 0, 0, 0, 0 }
};

int main(int argc, char *argv[])
{
        char *output = NULL;
        int i, opt, tofile = 0;
        bool msbc = false;

        while ((opt = getopt_long(argc, argv, "+hmvd:f:",
                                                main_options, NULL)) != -1) {
                switch(opt) {
                case 'h':
                        exit(0);

                case 'v':
                        break;

                case 'm':
                        msbc = true;
                        break;

                case 'd':
                        free(output);
                        output = strdup(optarg);
                        tofile = 0;
                        break;

                case 'f' :
                        free(output);
                        output = strdup(optarg);
                        //printf("%s",output);
                        tofile = 1;
                        break;

                default:
                        exit(1);
                }
        }

        argc -= optind;
        argv += optind;
        optind = 0;

        if (argc < 1) {
                exit(1);
        }


        for (i = 0; i < argc; i++)
                        printf("%s \n\t",argv[i]);

        free(output);

        return 0;
}

  運行結果:

## ./strfile -f test.wav new.wav testb.wav
new.wav
testb.wav

參考文檔:

https://blog.csdn.net/tigerjibo/article/details/12784823


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM