Using strdup

#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *s; s = strdup("foo"); printf("%s\n", s); getchar(); return 0; } 

Looks pretty harmless, doesn't it? But my IDE, which is Dev-C ++, gives the following warning: warning: assignment makes a pointer from an integer without cast

The warning disappears if you change the code as follows:

 char *s; s = (char*)strdup("foo"); 

enter image description here

Can someone help me explain this?

+4
source share
4 answers

You are using Dev-C ++, but strdup is not part of the C or C ++ standard, it is a POSIX function. You need to determine the correct (according to your IDE documentation) preprocessor characters so that strdup is declared a header file ... it is necessary that the header file does not pollute the namespace when included in the corresponding C or C ++ source files.

For a simple portable alternative, consider

 char* mystrdup(const char* s) { char* p = malloc(strlen(s)+1); if (p) strcpy(p, s); return p; } 

Or, if you know that strdup is actually in the library, you can copy its declaration from string.h to your own source file or header ... or use a simpler declaration from the man page:

 char *strdup(const char *s); 
+7
source

This is not true. strdup already returns char * . Something else is wrong. Perhaps because you did not include the right header file, which declares the true return type for this function.

 #include <string.h> 
+6
source

You are missing #include <string.h> . In the absence of function signatures, strdup is supposed to return an int by the compiler, hence a warning.

+1
source

man strdup

you will get the following things

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

therefore strdup() returns char* there was no problem Actually in your case an implicit declaration of strdup() is required, therefore the default return type is int , therefore, you get this warning

Or include<string.h>

or

give forward declaration char* strdup(const char *);

Also don't forget free(s) the last time all use is done

+1
source

Source: https://habr.com/ru/post/1446382/


All Articles