Tag: strdup

strdup()导致内存泄漏?

我已经实现了一个返回字符串的函数。 它将整数作为参数( age ),并返回格式化的字符串。 一切都运作良好,除了我有一些疯狂的内存泄漏。 我知道strdup()是导致这种情况的原因,但我试图研究一些修复无济于事。 我的代码是: const char * returnName(int age) { char string[30]; sprintf( string, “You are %d years old”, age); return strdup(string); } Valgrind的输出是: ==15414== LEAK SUMMARY: ==15414== definitely lost: 6,192 bytes in 516 blocks ==15414== indirectly lost: 0 bytes in 0 blocks ==15414== possibly lost: 0 bytes in 0 blocks ==15414== […]

当字符串文字以换行符\ n结尾时,strdup读取大小为4

当src字符串以\n结尾时,我收到无效的读取错误,当我删除\n时错误消失: #include #include #include int main (void) { char *txt = strdup (“this is a not socket terminated message\n”); printf (“%d: %s\n”, strlen (txt), txt); free (txt); return 0; } valgrind输出: ==18929== HEAP SUMMARY: ==18929== in use at exit: 0 bytes in 0 blocks ==18929== total heap usage: 2 allocs, 2 frees, 84 bytes allocated […]

从flex / bison中释放strdup()中分配的字符串

我有使用strdup()复制字符串lexeme的flex代码。 %{ #include “json.tab.h” #define YY_DECL extern “C” int yylex() %} %option noyywrap %% [ \t\n]+ ; \”[a-zA-Z]+\” {yylval.sval = strdup(yytext); return STRING; } [0-9]+ {yylval.ival = atoi(yytext); return NUMBER; } . {return yytext[0];} ; %% strdup()分配内存并将输入字符串复制到其中并返回( strdup() – 它在C中做了什么? ),所以我想我需要在我不再需要它时将其释放。 从这篇文章: 什么是在BISON中调用%析构函数? ,我添加了%destructor { free($$); printf(“free”);} STRING %destructor { free($$); printf(“free”);} STRING yacc文件中的%destructor { […]

strdup()函数

我最近意识到我喜欢在OS X上使用的strdup()函数不是ANSI C的一部分,而是POSIX的一部分。 我不想重写我的所有代码,所以我想我只是要编写自己的strdup()函数。 它并不难,真的,它只是一个malloc()和一个strcpy() 。 无论如何,我有这个function,但是如果我编写这个函数并将它链接到我的代码,我该怎么做,它已经存在于libc中了? 我的链接器或编译器是否允许我基本上定义我自己的函数版本,还是我必须给它另一个名字? 如果有一种方法可以重用相同的名称,那将非常方便,因此如果用户的libc中存在strcpy() ,则可以使用它,但如果它们的libc中不存在,则可以使用我的版本,因为代码变化很小。 简短版本: a)当我用与内置函数相同的名称编写自己的函数时会发生什么? b)我可以做些什么来避免在没有strdup()平台上发生不好的事情而不重写我的所有代码而不使用strdup() ,这有点单调乏味?