snd_pcm_drain: Assertion `pcm' failed. What might be the problem? This happens when I call :
int Capture(){
if(capture_handle)
return -1;
/* drop any output we might got and stop */
snd_pcm_drain(capture_handle);
/* prepare for use */
snd_pcm_prepare(capture_handle);
return 0;
}
The problem is that capture_handle is NULL.
You cannot drain a device that does not exist.
Related
I am trying to exit a program without using exit(). I have come up with a very convoluted and dirty solution (I am a Beginner).
I would like to use if statements and if it is true, then I would like to use goto to go the main function and then return 3; and end the program.
Here is a bit of code:
FILE *filepointer;
char * line = NULL;
size_t len = 0;
size_t read;
int linecount = 0;
filepointer = fopen(filename, "r");
if (filepointer == NULL)
{
printf("[ERR] Could not read file %s.\n",filename );
goto FILE_ERROR;
}
...
int main(){
...
FILE_ERROR: return 3;
}
This however does not work as I cannot get jump between functions because I get undeclared Label as an error. Is there any way I can exclude exit() from my program and still end it returning a certain value. If there is a better solution, please let me know
The only good answer to this question is: don't do it. gotos used in this way make your code very hard to reason about.
Refactor your code so that you have a clear structure and hierarchy of calls. Use return values to propagate success/failure throughout the call stack.
goto can't be used to jump across different functions; it can only be used within the same function. To jump between functions, you can look at setjmp() and longjmp() functions.
Having said, since you claim to be a beginner, I am not convinced you really need to use either of the above. You can simply modify your function to return an "error" value. And in main(), check its value and return from main() with the error value.
By design, a goto cannot jump from one function to another. It can only be used to jump within a given function.
There are ways to jump between functions, but doing so is not only very poor design but also dangerous as it is very easy to put your program in an invalid state.
The proper way to handle this is to have your function return a specific value (or set of values) to indicate an error. Then the calling function would check for one of those error values and act accordingly.
For example:
int readFile(char *filename)
{
FILE *filepointer;
char * line = NULL;
size_t len = 0;
size_t read;
int linecount = 0;
filepointer = fopen(filename, "r");
if (filepointer == NULL)
{
// add strerror(error) to the error message to know why fopen failed
printf("[ERR] Could not read file %s: %s.\n",filename, strerror(errno) );
// error completion
return 0;
}
...
// successful completion
return 1;
}
int main(){
...
if (readFile("myfile") == 0) {
return 3;
}
...
}
If you wanted to use a go-to , and insisted on doing that, you could I guess try to expand your 1st function so it includes / encapsulates the 2nd function, and get rid of the 2nd function conpletely, so your able to do go tos and subroutines within this much larger function.
Is that an option you could try ? (If you were dead cert on using Goto's, ) ?
I would give that a go.
I have a basic question regarding proper program structure in c.
Let's say my main function calls several other functions to configure a specific piece of hardware (like an ethernet card), and that each of those functions calls more basic functions to deal with more specific configuration on that ethernet card.
The the lower level functions all have return values that specify whether they were completed successfully. Is it most proper to continue this paradigm all the way back to main?
For example, if one of my lower level functions fails, should I be doing the following?:
check its return value --> return to calling function --> check its return value --> return to calling function ...
all the way back to main?
Or does it make more sense to have main just assume everything is functioning normally (not considering return values of the functions it calls) and returning 0; then calling exit(EXIT_FAILURE) from the lower level functions?
I greatly appreciate the help.
For academia level applications, I don't think it matters.
.
However, for production (enterprise) applications, my (30-years) experience is:
1) Never call exit() unless it's a last resort, where the user needs to
contact the application developer to resolve an unanticipated condition.
2) In order to ensure maintainability, functions should not contain more
than one return statement.
All of the functions I produce (for use in an enterprise production environment) have a similar flow:
int SomeEnterpriseQualityFunction(
SOME_TYPE1_T I__someValueBeingPassedIntoTheFunction,
...
SOME_TYPE2_T *IO_someValueBeingModifiedByTheFunction,
...
SOME_TYPE3_T **_O_someValueBeingReturnedByTheFunction
)
{
int rCode=0;
int someFileHandle=(-1);
void *someMemory = NULL;
SOME_TYPE3_T *someValueBeingReturnedByTheFunction=NULL;
/* Validate user input parameters */
if( /*I__someValueBeingPassedIntoTheFunction is out of range */)
{
rCode=ERANGE;
goto CLEANUP;
}
if( NULL == IO_someValueBeingModifiedByTheFunction )
{
rCode=EINVAL;
goto CLEANUP;
}
/* Acquire resources */
someFileHandle=open(/*someFileName, mode, etc.*/);
if((-1) == someFileHandle)
{
rCode=errno;
goto CLEANUP;
}
someMemory=malloc(/* bytesToMalloc */);
if(NULL == someMemory)
{
rCode=ENOMEM;
goto CLEANUP;
}
/* Actual work done here. */
....
if(/* Successfully finished work at this point... */)
goto RESULT;
...
...
/* Return results to caller here. */
RESULT:
if(_O_someValueBeingReturnedByTheFunction);
{
*_O_someValueBeingReturnedByTheFunction = someValueBeingReturnedByTheFunction;
someValueBeingReturnedByTheFunction = NULL;
}
/* Release acquired resources. */
CLEANUP:
if(someValueBeingReturnedByTheFunction)
{
int rc= /* Clean-up someValueBeingReturnedByTheFunction related resources,
since the caller didn't need it. */
if(0==rCode)
rCode=rc;
}
if(someMemory)
free(someMemory);
if((-1) != someFileHandle)
{
if((-1) == close(someFileHandle) && 0 == rCode)
rCode=rc;
}
return(rCode);
}
And, not matter what your instructors might say about goto, they are far from -evil- when used in this way for error handling.
There are multiple separate issues here.
As for whether you should propagate errors up or just call exit(EXIT_FAILURE) at the point you detect a problem, I'd generally recommend propagating the errors up. If the low-level code propagates the error up, it leaves open the possibility that the higher-level code could try to handle the error (e.g., report it to the user, retry, try a different configuration, etc.). If the low-level code bails out, the higher level code doesn't have a chance to deal with it. (The flipside is that the higher level code has to be prepared to do something appropriate and not just carry on assuming there were no errors.)
As for what those errors values should be, I'd generally recommend defining your own return status types (e.g., as an enum). EXIT_FAILURE and EXIT_SUCCESS are intended to be inputs to exit, and you should treat them as opaque values. For example, don't assume that EXIT_SUCCESS is 0.
As for whether you should return from main or call exit, that's up to you. To be super-hyper-portable, I recommend calling exit with EXIT_SUCCESS or EXIT_FAILURE as appropriate. However, it's common to simply return 0 for success or return nonzero for failure. The latter practice doesn't work well on some obscure, mostly dead operating systems with brain-dead compilers. In any event, I would never return EXIT_SUCCESS from main.
In my opinion, calling exit( EXIT_FAILURE ) right from the failing function is okay. If some cleanup is necessary, then I would use atexit()
From http://linux.die.net/man/3/exit
#include <stdlib.h>
void exit(int status);
The exit() function causes normal process termination ...
All functions registered with atexit(3) and on_exit(3) are called,
in the reverse order of their registration.
I am a newbie at C programming and new on Stackoverflow as well.
I have some c code that compiles and runs in Eclipse Kepler (Java EE IDE); I installed the C/C++ plugin and Cygwin Gcc compiler for c.
Everything runs ok in Eclipse IDE; however, when my friend tries to run the same code on his Codeblocks IDE, he doesn't get any output. At some point, he got some segmentation error, which we later learned was due to our program accessing memory space that didn't belong to our program.
Codeblocks IDE is using Gcc compiler not cygwin gcc, but I don't think they're that different to cause this sort of problem.
I am aware that C is extremely primitive and non-standardized, but why would my code run in eclipse with cygwin-gcc compiler but not run in Codeblocks IDE with gcc compiler?
Please help, it's important for our class project.
Thanks to all.
[EDIT] Our code is a little large to paste in here but here's a sample code of what would RUN SUCCESSFULLY in eclipse but FAIL in codeblocks, try it yourself if you have codeblocks please:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main(void) {
char *traceEntry1;
FILE *ifp;
traceEntry1 = malloc(200*sizeof(char));
ifp = fopen("./program.txt", "r");
while (fgets(traceEntry1, 75, ifp))
printf("String input is %s \n", traceEntry1);
fclose(ifp);
}
It simply doesn't give any outputs in codeblocks, sometimes just results in a segmentation fault error.
I have no idea what the problem is.
We need your help please, thanks in advance.
Always and ever test the results of all (revelant) calls. "relevant" at least are those call which return results which are unusable if the call failed.
In the case of the OP's code they are:
malloc()
fopen()
fclose()
A save version of the OP's code could look like this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int result = EXIT_SUCCESS; /* Be optimistic. */
char * traceEntry1 = NULL; /* Always initialise your variables, you might remove this during the optimisation phase later (if ever) */
FILE * ifp = NULL; /* Always initialise your variables, you might remove this during the optimisation phase later (if ever) */
traceEntry1 = malloc(200 * sizeof(*traceEntry1)); /* sizeof(char) is always 1.
Using the dereferenced target (traceEntry1) on the other hand makes this
line of code robust against modifications of the target's type declaration. */
if (NULL == traceEntry1)
{
perror("malloc() failed"); /* Log error. Never ignore useful and even free informaton. */
result = EXIT_FAILURE; /* Flag error and ... */
goto lblExit; /* ... leave via the one and only exit point. */
}
ifp = fopen("./program.txt", "r");
if (NULL == ifp)
{
perror("fopen() failed"); /* Log error. Never ignore useful and even free informaton. */
result = EXIT_FAILURE; /* Flag error ... */
goto lblExit; /* ... and leave via the one and only exit point. */
}
while (fgets(traceEntry1, 75, ifp)) /* Why 75? Why not 200 * sizeof(*traceEntry1)
as that's what was allocated to traceEntr1? */
{
printf("String input is %s \n", traceEntry1);
}
if (EOF == fclose(ifp))
{
perror("fclose() failed");
/* Be tolerant as no poisened results are returned. So do not flag error. It's logged however. */
}
lblExit: /* Only have one exit point. So there is no need to code the clean-up twice. */
free(traceEntry1); /* Always clean up, free what you allocated. */
return result; /* Return the outcome of this exercise. */
}
I want to read a file in a specific format, so I use fscanf_s and a while loop. But as soon as fscanf_s is processed, the program crashes with an access violation (0xC0000005).
Here's the code:
FILE *fp;
errno_t err = fopen_s(&fp, "C:\\data.txt", "r");
if (err != 0)
return 0;
int minSpeed = 0;
int maxSpeed = 0;
char axis = '#';
while(!feof(fp))
{
int result = fscanf_s(fp, "%c;%d-%d\n", &axis, &minSpeed, &maxSpeed);
if (result != 3)
continue;
}
fclose(fp);
The content of the file is line based, for example:
-;10000-20000
X;500-1000
S;2000-2400
Can somebody help me?
Apparently, fscanf_s() needs a size parameter after the address of the variable
fscanf_s(fp, "%c;%d-%d\n", &axis, 1, &minSpeed, &maxSpeed);
/* extra 1 for the size of the ^^^ axis array */
But I suggest you do not use the *_s functions: they are worse than the plainly named functions --- they require the same checks and make you feel safe when you aren't. I suggest you don't use them because of false sense of security and the fact they are not available on many implementations making your programs work only in a limited subset of possible machines.
Use plain fscanf()
fscanf(fp, "%c;%d-%d\n", &axis, &minSpeed, &maxSpeed);
/* fscanf(fp, "%1c;%d-%d\n", &axis, &minSpeed, &maxSpeed); */
/* default 1 ^^^ same as for fscanf_s */
And your use of feof() is wrong.
The fscanf() returns EOF when there is an error (end-of-file or matching failure or read error ...).
You can use feof() to determine why fscanf() failed, not to check whether it would fail on the next time it is called.
/* pseudo-code */
while (1) {
chk = fscanf();
if (chk == EOF) break;
if (chk < NUMBER_OF_EXPECTED_CONVERSIONS) {
/* ... conversion failures */
} else {
/* ... all ok */
}
}
if (feof()) /* failed because end-of-file reached */;
if (ferror()) /* failed because of stream error */;
If you believe the file (data.txt) exists, your application is probably not running with a current directory set to where the file is. This would cause fopen_s() to fail.
I have a bit of queue code that I was working on. I was trying to use a global int to keep track of the queue's size.
#define MAX 100
int size=0;
int gEnqueue=gDequeue=0;
int enqueue()
{
gEnqueue++;
if( size == MAX )
return QUEUE_FULL;
/* snip the actual queue handling */
size++;
return 0;
}
int dequeue()
{
gDequeue++;
if(!size)
return QUEUE_EMPTY;
/* snip actual queue handling */
if(size)
size--;
return 0;
}
there is of course much more code then that, but too much to post.
What is happening is the size gets stuck at the max I have set. Both functions get called an even number of times. If I dump the queue I can see that there are only 3 items in it.
What would cause this problem?
edit #1: made the code example match what I actually coded
This is not threaded.
edit #2: I am an idiot and should have done this instead of assuming.
I was wrong about the calls being even to the enqueue() and dequeue().
Note to self, use real metrics not guesses.
If you can't use a debugger I would suggest adding print statements inside both functions showing what size equals and then after running the program examine the output. Usually when looking at the print log the problem is pretty obvious.
The easiest solution is not to call "enqueue" if size==MAX.
But if that's not possible try this:
int size=0;
int overflow=0;
int enqueue()
{
if( size < MAX )
size++;
else
overflow++;
return 0;
}
int dequeue()
{
if(overflow)
overflow--;
else if(size)
size--;
return 0;
}
There's nothing obviously wrong with the code you posted, so this suggests there's something wrong with the code you snipped, or in the way you're calling the code. You'll have to debug this for yourself. There are two main debugging techniques that would help you at this point:
As #KPexEA suggested, debugging using printf() or other logging statements. Put a printf() at the beginning and end of both functions, printing out as much state as you think might possibly be useful.
int enqueue()
{
printf("enqueue(): Enter: size=%d\n", size);
if( size == MAX ) {
printf("enqueue(): Exit: QUEUE_FULL\n");
return QUEUE_FULL;
}
/* snip the actual queue handling */
size++;
printf("enqueue(): Exit: size=%d\n", size);
return 0;
}
int dequeue()
{
printf("dequeue(): Enter: size=%d\n", size);
if(!size) {
printf("dequeue(): QUEUE_EMPTY\n");
return QUEUE_EMPTY;
}
/* snip actual queue handling */
if(size)
size--;
printf("dequeue(): Exit: size=%d\n", size);
return 0;
}
By examining the output, it should become apparent what's happening with the size of your queue. (You could also count the actual number of elements in your queue and print that when you enter and exit your functions.)
The other technique is interactive debugging. This is especially useful to determine exactly how your code is flowing, but you have to sit there every time you run your program to watch how it's running. (If your bug occurs every time, that's easy; if it occurs every once and a while, it's hard to go back and recreate your program's flow after the fact.) Set a breakpoint at the beginning of each of your functions and use the debugger to display the value size. Set another breakpoint at the end of each function and make sure (1) the breakpoint actually gets hit, and (2) your expectations of any changes made to size are met.