简体   繁体   English

比较strdup函数的返回值和strncmp

[英]comparing a return from strdup function, with strncmp

I am new to C language. 我是C语言的新手。 I am trying to compare two returned values from strdup , with the strncmp function, but getting following error: 我正在尝试将strdup两个返回值与strncmp函数进行比较,但出现以下错误:

error: passing argument 2 of 'strncmp' makes pointer from integer without a cast [-Wint-conversion] 错误:传递'strncmp'的参数2使指针从整数开始而没有强制转换[-Wint-conversion]

my code: 我的代码:

if (0 == strncmp( strdup(str_to_dup1), strdup(str_to_dup2)))

From strncmp strncmp

strncmp strncmp

int strncmp( const char *lhs, const char *rhs, size_t count ); int strncmp(const char * lhs,const char * rhs,size_t count);复制代码

In you code, you are missing the third argument of strncmp which is the maximum number of character to compare. 在您的代码中,您缺少了strncmp的第三个参数,它是要比较的最大字符数。

Your program is having potential memory leak as the pointer returned by strdup() will be lost after strncmp() call. 您的程序可能存在内存泄漏,因为在strncmp()调用后, strdup()返回的指针将丢失。 Also, you should be aware that strdup() can return null pointer if an error occurred. 另外,您应该知道,如果发生错误, strdup()可以返回null指针。

You should take the strdup() returned pointer to a variable and make sure to check for if some error is occurred and then pass those variables to strncmp() . 您应该将strdup()返回的指针指向一个变量,并确保检查是否发生了某些错误,然后将这些变量传递给strncmp() Once done with strdup() returned pointers, free them using free() . 一旦使用strdup()返回的指针,就可以使用free()释放它们。

strncmp takes 3 parameters like below strncmp接受如下三个参数

int strncmp(const char *str1, const char *str2, size_t n)

in your code missing the third parameter, the max number characters to be compared 您的代码中缺少第三个参数,即要比较的最大字符数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM