errors occurred while compiling on gcc - c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(void)
{
int a,b,sub,i,count=0;char buffer[20],w[20];
scanf("%d",&a);
scanf("%d",&b);
sub=a-b;
if(sub>0)
{
scanf("%s",w); /*wrong answer*/
itoa(sub,buffer,10);
int l=strlen(buffer);
for(i=0;i<l;i++)
{
if(w[i]==buffer[i])
count++;
}
((count==l || count==l-1) && w[0]!='0') ? printf("accepted") : printf("Not accepted");
}
else printf("Sub operation returned negative value");
}
The output of the compiler is
prog.c:4:6: warning: return type of 'main' is not 'int' [-Wmain]
void main(void)
^
prog.c: In function 'main':
prog.c:13:1: warning: implicit declaration of function 'itoa' [-Wimplicit-function-declaration]
itoa(sub,buffer,10);
^
/home/HCDVgj/ccHBnrc7.o: In function `main':
prog.c:(.text.startup+0x61): undefined reference to `itoa'
collect2: error: ld returned 1 exit status
I did not use any long int variables but i still get ld return 1 exists. how to debug these errors

int main() This is teh first thing you should do.
scanf("%19s",w); This is better.
itoa is non standard (so you will not find it in any standard implementaion) better use snprintf()
printf('%s",((count==l || count==l-1) && w[0]!='0') ? "accepted" : "Not accepted"); More compact I would say.
Use of snprintf
snprintf(target, size_of_target1, "%d", source2);
sprintf takes no parameter specifying the number of bytes to write which may lead to buffer overflow which is not a good thing.
1 : In bytes
2 : source is in integer here
Few things worth mentioning to clear your idea or to be more precise
The output you specified is not output of the c program ... in the process of compilation your compiler run into error and then it generates those output. -CiaPan
main() shouldn't be of void return type it is expected to return 0 in case of normal termination. Abnormal termination is usually signaled by a non-zero.-David C. Rankin

I don't know why you're talking about "long int variables".
The first warning can be fixed by changing void main(void) to int main(void) and adding a return 0; at the end.
The second warning tells you that the compiler doesn't know what itoa is.
The following linker error tells you that the linker (ld) also doesn't know what itoa is, and that's why compilation fails.
The reason itoa is unknown is that it's not a standard function and not available on your platform.

Related

Mingw -- Conflicting types for function due to previous declaration

To start off, I don't get this issue when I compile/"make" the code on a Linux machine which I connect to remotely. I'm experiencing it only on my Windows laptop with Mingw installed -- which I believe is causing the issue.
$ make
gcc -c parser.c
parser.c:34:7: error: conflicting types for 'gets'
34 | char* gets(char *buf, int max)
| ^~~~
In file included from parser.h:4,
from parser.c:1:
c:\mingw\include\stdio.h:709:41: note: previous declaration of 'gets' was here
709 | _CRTIMP __cdecl __MINGW_NOTHROW char * gets (char *);
| ^~~~
Makefile:13: recipe for target 'parser.o' failed
make: *** [parser.o] Error 1
Here's the gets() code as requested:
char* gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
cc = read(0, &c, 1);
if(cc < 1) break;
//c = getchar();
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
return buf;
}
Is there a way to fix this without changing the gets function name? Thank you sm
Your code works on Linux's gcc because the gets function was removed, as it should, since it was deprecated in the C99 standard and removed with C11.
For some reason the Windows MingW distribution still maintains gets and because of that you have a redefinition problem.
So unfortunately you can't use that function name, unless you remove it by hand from stdio.h, as C doesn't allow for function overloading.
Running sample on Linux gcc
Running sample on Windows gcc
As the error says the gets() function is already defined in stdio.h.
One trick you can do is put something like this:
#define gets MY_gets
before your definition of the gets() function.
That way you are actually defining a MY_gets() function which causes no conflict. And when you call gets() later on in your code you are actually calling MY_gets().
If you define gets() in a header file you should include stdio.h first and then put #define gets MY_gets before the declaration of gets() in the header file.
Though I don't see why you want to refine this function if it already exists.
It makes more sense to only define it if needed and surround the function with something like #ifndef HAVE_GETS and endif where HAVE_GETS should be defined based on tests done in the configure/build system.

How to handle error: expected expression before ‘do’ when there is no "do"?

I get the following compiler error, even though there is no "do" expression in my code.
gcc -Wall -g -c main.c -lasound
In file included from /usr/include/alsa/asoundlib.h:49:0,
from main.c:2:
main.c: In function ‘main’:
main.c:8:5: error: expected expression before ‘do’
if(snd_pcm_hw_params_alloca(&params) < 0) {
^
main.c:6:30: warning: unused variable ‘params’ [-Wunused-variable]
snd_pcm_hw_params_t *params;
^~~~~~
Makefile:15: recipe for target 'main.o' failed
make: *** [main.o] Error 1
From the following minimal reproducible example:
#include <stdio.h>
#include <alsa/asoundlib.h>
int main(int argc, char **argv)
{
snd_pcm_hw_params_t *params;
if(snd_pcm_hw_params_alloca(&params) < 0) {
return 0;
}
exit(0);
}
I'm aware this is not a valid ALSA program. I'm also aware that it appears snd_pcm_hw_params_alloca() doesn't even return anything worthwhile to check for errors against? That's not relevant though, this should valid C code regardless, even if it abuses the API.
Where is the "do" expression? If I go to /usr/include/alsa/asoundlib.h and poke around there, I don't see anything obvious that would indicate a problem.
If I remove the conditional if test, and get:
#include <stdio.h>
#include <alsa/asoundlib.h>
int main(int argc, char **argv)
{
snd_pcm_hw_params_t *params;
snd_pcm_hw_params_alloca(&params);
exit(0);
}
This will compile with no errors.
What is this?
If I look in pcm.h, I see:
#define snd_pcm_hw_params_alloca(ptr) __snd_alloca(ptr, snd_pcm_hw_params)
int snd_pcm_hw_params_malloc(snd_pcm_hw_params_t **ptr);
void snd_pcm_hw_params_free(snd_pcm_hw_params_t *obj);
void snd_pcm_hw_params_copy(snd_pcm_hw_params_t *dst, const snd_pcm_hw_params_t *src);
However, this doesn't tell me anything. Why does the compiler produce this error?
I'm also aware that it appears snd_pcm_hw_params_alloca() doesn't even return anything worthwhile to check for errors against? That's not relevant though, this should valid C code regardless, even if it abuses the API.
No, if snd_pcm_hw_params_alloca() does not have a value you cannot compare it against 0. For example, the following is also invalid:
void func(void) { }
void other(void) {
if (func() < 0) { // Error
}
}
In reality, snd_pcm_hw_params_alloca() is a macro, and it’s a wrapper for another macro, __snd_alloca. The do is there to make it behave more like a statement. You can only call it as a statement on its own line, or anywhere else where a do loop is legal.
snd_pcm_hw_params_alloca(&params);
You cannot check for errors because alloca() does not check for errors. If alloca() fails, it will just stomp on your stack, and bad things will happen. You can’t do anything about it, except not use alloca() (this is why you might hear advice to avoid alloca).
For an explanation of why the do loop is used, see: C multi-line macro: do/while(0) vs scope block
For more information about how alloca() works, see: Why is the use of alloca() not considered good practice?

fgets produces the compiling error "ignoring return value of 'fgets', declared with attribute wan_unused_result" [duplicate]

#include <stdio.h>
int main() {
int t;
scanf("%d", &t);
printf("%d", t);
return 0;
}
I compiled the above C code using ideone.com and the following warning popped up:
prog.c: In function ‘main’:
prog.c:5: warning: ignoring return value
of ‘scanf’, declared with attribute warn_unused_result
Can someone help me understand this warning?
The writer's of your libc have decided that the return value of scanf should not be ignored in most cases, so they have given it an attribute telling the compiler to give you a warning.
If the return value is truly not needed, then you are fine. However, it is usually best to check it to make sure you actually successfully read what you think you did.
In your case, the code could be written like this to avoid the warning (and some input errors):
#include <stdio.h>
int main() {
int t;
if (scanf("%d", &t) == 1) {
printf("%d", t);
} else {
printf("Failed to read integer.\n");
}
return 0;
}
The warning (rightly) indicates that it is a bad idea not to check the return value of scanf. The function scanf has been explicitly declared (via a gcc function attribute) to trigger this warning if you discard its return value.
If you really want to forget about this return value, while keeping the compiler (and your conscience) happy, you can cast the return value to void:
(void)scanf("%d",&t);
I tried your example with gcc (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3.
The warning is issued if and only if optimizing, e.g., with option -O2 or -O3.
Requesting all warnings (-Wall) doesn't matter.
The classic idiom of casting to void has no effect, it does not suppress the warning.
I can silence the warning by writing
if(scanf("%d",&t)){};
this works, but it's a bit obscure for my taste. Empty {} avoids yet another warning -Wempty-body
Do this:
int main() {
int t;
int unused __attribute__((unused));
unused = scanf("%d",&t);
printf("%d",t);
return 0;
}
After reading all answers and comments on this page I don't see these yet another options to avoid the warning:
When compiling with gcc you can add to your command line:
gcc -Wall -Wextra -Wno-unused-result proc.c -o prog.x
Another option is to use -O0 as "optimization level zero" ignores the warning.
Using cast to (void) is simply useless when compiling with gcc
If debugging your code, you can always use assert() as in the example bellow:
u = scanf("%d", &t);
assert(u == 1);
But now, if you turn off assert via #define NDEBUG you will get a -Wunused-but-set-variable. You can then turn off this second warning by one of two ways:
Adding -Wno-unused-but-set-variable to your gcc command line, or
Declaring the variable with attribute: int u __attribute__((unused));
As pointed out in other answer, the second option unfortunately is not very portable, although it seems the best option.
At last, the defined MACRO bellow can help you if you are sure you want to ignore the return of a given function, but you are not comfortable turning off the warnings for all unused returns of functions:
#define igr(x) {__typeof__(x) __attribute__((unused)) d=(x);}
double __attribute__ ((warn_unused_result)) fa(void) {return 2.2;}
igr(fa());
See also this answer
One way to solve this is the IGUR() function as seen below. Extremely ugly, but nevertheless somewhat portable. (For old compilers which do not understand inline just #define inline /*nothing*/, as usual.)
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
inline void IGUR() {} /* Ignore GCC Unused Result */
void IGUR(); /* see https://stackoverflow.com/a/16245669/490291 */
int
main(int argc, char **argv)
{
char buf[10*BUFSIZ];
int got, fl, have;
fl = fcntl(0, F_GETFL);
fcntl(0, F_SETFL, fl|O_NONBLOCK);
have = 0;
while ((got=read(0, buf, sizeof buf))>0)
{
IGUR(write(1, buf, got));
have = 1;
}
fcntl(0, F_SETFL, fl);
return have;
}
BTW this example, nonblockingly, copies from stdin to stdout until all waiting input was read, returning true (0) if nothing was there, else false (1). (It prevents the 1s delay in something like while read -t1 away; do :; done in bash.)
Compiles without warning under -Wall (Debian Jessie).
Edit: IGUR() needs to be defined without inline, too, such that it becomes available for the linker. Else with cc -O0 it might fail. See: https://stackoverflow.com/a/16245669/490291
Edit2: Newer gcc require inline to be before void.
Actually it depends on what you need, if you just want to disable the warning of compiler, you can just ignore the return value of the function by the force conversion or you can just handle it, the meaning of the scanf function is the count of user input.
==== update ====
You can use
(void) scanf("%d",&t);
to ignore the return value of scanf
Can someone help me understand this warning?
No, but here is my contribution to the horror of warning suppression. To actively throw the return value out the window, elegance dictates wrapping our statement in a comprehensible lambda function, like this:
[&]{ return scanf("%d", &t); }();
My apologies.
scanf, printf is functions that returns value, usually in those kind of functions it's the amount of characters read or written. if an error occurs, you can catch the error also with the return code.
A good programming practice will be to look at the return value, however, I never saw someone who looks at the printf return value...
If you want the warning to disappear, you can probably change the severity of the compiler.
Since functions without arguments are valid in C, you can do the following:
#include <stdio.h>
static inline void ignore_ret() {}
int main() {
int t;
ignore_ret(scanf("%d", &t));
return 0;
}
just use a surrunding if () and an empty block, the terminating semikolon has to be in the next line (to prevent additional warnings)
#include <stdio.h>
main (int argc, char const *argv[]) {
...
if ( scanf("%d",&n) )
;
...
return 0;
}

Beginner C programmer having problems with string functions

I'm a C noob, going back to school for my masters in CS so I'm taking some time to ramp up my skills. I wanted to see if anybody could lend some assistance on why I'm having problems compiling the following code. I've been following the videos on WiBit.net and develop on a 64 bit Linux environment (Ubuntu 13.10). I am using gedit and the gcc compiler no IDE.
This code runs on my Win 7 VM without errors, however when I try to execute it on my host Linux environment I'm getting errors:
Source Code: This example calls the strcmp and strcmpi functions
#include <stdio.h>
#include <string.h>
int main()
{
char str1[255];
char str2[255];
printf("str1: "); gets(str1);
printf("str2: "); gets(str2);
if(strcmp(str1, str2) == 0)
printf("Strings match exactly!");
else if(strcmpi(str1, str2) == 0)
printf("Strings match when ignoring case!");
return 0;
}
Error Message (Linux ONLY):
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1
/tmp/ccwqdQMN.o: In function main':
main.c:(.text+0x25): warning: thegets' function is dangerous and should not be used.
main.c:(.text+0x8f): undefined reference to `strcmpi'
collect2: error: ld returned 1 exit status
Source Code 2: This example uses the strupr and strlwr functions
#include <stdio.h>
#include <string.h>
int main()
{
char str1[255];
char str2[255];
printf("str1: "); gets(str1);
printf("str2: "); gets(str2);
strlwr(str1);
strupr(str2);
puts (str1);
puts (str2);
return 0;
}
Error Message (Linux ONLY):
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1
/tmp/ccWnIfnz.o: In function main':
main.c:(.text+0x25): warning: thegets' function is dangerous and should not be used.
main.c:(.text+0x57): undefined reference to strlwr'
main.c:(.text+0x6b): undefined reference tostrupr'
collect2: error: ld returned 1 exit status
I would love a detailed explanation if someone is willing to help and not tear me apart haha. I know that for best practices we shouldn't use gets due to buffer overflow (for example the user enters a 750 character string). Best practices would use fgets instead but my question is whether I'm getting these errors because these functions aren't part of ANSI C or what. They do show up in the man files on my machine which is throwing me through a loop.
Thanks in advance!
UPDATE:
You guys are awesome. Took all of your advice and comments and was able to revise and make a sample program for string comparison as well as conversion to upper/lower. Glad I was able to get it running on both OSes error free as well.
Sample code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char str[255];
printf("Enter a string: "); fgets(str,255, stdin);
printf("Here is your original string, my master: %s\n", str);
//Now let's loop through and convert this to all lowercase
int i;
for(i = 0; str[i]; i++)
{
str[i] = tolower(str[i]);
}
printf("Here is a lowercase version of your string, my master: %s\n", str);
//Now we'll loop through and convert the string to uppercase
int j;
for(j = 0; str[j]; j++)
{
str[j] = toupper(str[j]);
}
printf("Here is a uppercase version of your string, my master: %s\n", str);
return 0;
}
strcmpi problem: strcasecmp() is the posix standard and so is it in linux.
strupr and strlwr doesn't exist in glibc, although you can implement them with a single line of code, as this:
c - convert a mixed-case string to all lower case
In the compilation, first you can find a warning, because the gcc doesn't find the functions in the included header. In such cases it thinks they are declared as int funcname(void). But later, while linking, it can't find the exported symbols of this nonexistant functions, and thus it can't create the executable. This second error is what stops the compilation.
There are too many difference in the c apis, although the posix standard handles them, microsoft don't follow it.
As you noted, the gets function is unsafe because it does not perform any boundary checking: you have called it with a 255-character string buffer, but if another program wrote a line longer than 255 characters, it could write data into your process's stack, and thereby cause your process to execute malicious code (or at the very least produce a segmentation fault).
Use fgets instead:
printf("str1: "); fgets(str1, 255, stdin);
printf("str2: "); fgets(str2, 255, stdin);
If you read the error output from the compiler carefully, you'll note that it's not issuing an error on your use of gets but a warning. Your code should still compile and execute if you fix the strcmpi call.

Warning: ignoring return value of 'scanf', declared with attribute warn_unused_result

#include <stdio.h>
int main() {
int t;
scanf("%d", &t);
printf("%d", t);
return 0;
}
I compiled the above C code using ideone.com and the following warning popped up:
prog.c: In function ‘main’:
prog.c:5: warning: ignoring return value
of ‘scanf’, declared with attribute warn_unused_result
Can someone help me understand this warning?
The writer's of your libc have decided that the return value of scanf should not be ignored in most cases, so they have given it an attribute telling the compiler to give you a warning.
If the return value is truly not needed, then you are fine. However, it is usually best to check it to make sure you actually successfully read what you think you did.
In your case, the code could be written like this to avoid the warning (and some input errors):
#include <stdio.h>
int main() {
int t;
if (scanf("%d", &t) == 1) {
printf("%d", t);
} else {
printf("Failed to read integer.\n");
}
return 0;
}
The warning (rightly) indicates that it is a bad idea not to check the return value of scanf. The function scanf has been explicitly declared (via a gcc function attribute) to trigger this warning if you discard its return value.
If you really want to forget about this return value, while keeping the compiler (and your conscience) happy, you can cast the return value to void:
(void)scanf("%d",&t);
I tried your example with gcc (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3.
The warning is issued if and only if optimizing, e.g., with option -O2 or -O3.
Requesting all warnings (-Wall) doesn't matter.
The classic idiom of casting to void has no effect, it does not suppress the warning.
I can silence the warning by writing
if(scanf("%d",&t)){};
this works, but it's a bit obscure for my taste. Empty {} avoids yet another warning -Wempty-body
Do this:
int main() {
int t;
int unused __attribute__((unused));
unused = scanf("%d",&t);
printf("%d",t);
return 0;
}
After reading all answers and comments on this page I don't see these yet another options to avoid the warning:
When compiling with gcc you can add to your command line:
gcc -Wall -Wextra -Wno-unused-result proc.c -o prog.x
Another option is to use -O0 as "optimization level zero" ignores the warning.
Using cast to (void) is simply useless when compiling with gcc
If debugging your code, you can always use assert() as in the example bellow:
u = scanf("%d", &t);
assert(u == 1);
But now, if you turn off assert via #define NDEBUG you will get a -Wunused-but-set-variable. You can then turn off this second warning by one of two ways:
Adding -Wno-unused-but-set-variable to your gcc command line, or
Declaring the variable with attribute: int u __attribute__((unused));
As pointed out in other answer, the second option unfortunately is not very portable, although it seems the best option.
At last, the defined MACRO bellow can help you if you are sure you want to ignore the return of a given function, but you are not comfortable turning off the warnings for all unused returns of functions:
#define igr(x) {__typeof__(x) __attribute__((unused)) d=(x);}
double __attribute__ ((warn_unused_result)) fa(void) {return 2.2;}
igr(fa());
See also this answer
One way to solve this is the IGUR() function as seen below. Extremely ugly, but nevertheless somewhat portable. (For old compilers which do not understand inline just #define inline /*nothing*/, as usual.)
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
inline void IGUR() {} /* Ignore GCC Unused Result */
void IGUR(); /* see https://stackoverflow.com/a/16245669/490291 */
int
main(int argc, char **argv)
{
char buf[10*BUFSIZ];
int got, fl, have;
fl = fcntl(0, F_GETFL);
fcntl(0, F_SETFL, fl|O_NONBLOCK);
have = 0;
while ((got=read(0, buf, sizeof buf))>0)
{
IGUR(write(1, buf, got));
have = 1;
}
fcntl(0, F_SETFL, fl);
return have;
}
BTW this example, nonblockingly, copies from stdin to stdout until all waiting input was read, returning true (0) if nothing was there, else false (1). (It prevents the 1s delay in something like while read -t1 away; do :; done in bash.)
Compiles without warning under -Wall (Debian Jessie).
Edit: IGUR() needs to be defined without inline, too, such that it becomes available for the linker. Else with cc -O0 it might fail. See: https://stackoverflow.com/a/16245669/490291
Edit2: Newer gcc require inline to be before void.
Actually it depends on what you need, if you just want to disable the warning of compiler, you can just ignore the return value of the function by the force conversion or you can just handle it, the meaning of the scanf function is the count of user input.
==== update ====
You can use
(void) scanf("%d",&t);
to ignore the return value of scanf
Can someone help me understand this warning?
No, but here is my contribution to the horror of warning suppression. To actively throw the return value out the window, elegance dictates wrapping our statement in a comprehensible lambda function, like this:
[&]{ return scanf("%d", &t); }();
My apologies.
scanf, printf is functions that returns value, usually in those kind of functions it's the amount of characters read or written. if an error occurs, you can catch the error also with the return code.
A good programming practice will be to look at the return value, however, I never saw someone who looks at the printf return value...
If you want the warning to disappear, you can probably change the severity of the compiler.
Since functions without arguments are valid in C, you can do the following:
#include <stdio.h>
static inline void ignore_ret() {}
int main() {
int t;
ignore_ret(scanf("%d", &t));
return 0;
}
just use a surrunding if () and an empty block, the terminating semikolon has to be in the next line (to prevent additional warnings)
#include <stdio.h>
main (int argc, char const *argv[]) {
...
if ( scanf("%d",&n) )
;
...
return 0;
}

Resources