Answer the question
In order to leave comments, you need to log in
Why does a segmentation fault appear, but when the program is restarted, it does not?
I need to turn gpio38 on and off for this, I use C++ code, but once every other time a segmentation fault error pops up (that is, the first time I started everything normally, the second time I started the error, the third everything is fine, the fourth error, and so on, without changing anything in the code)
/* gpio38.c */
#include <stdio.h>
#include <stdlib.h>
#define GPIO_PATH "/sys/class/gpio"
#define GPIO38_PATH “/sys/class/gpio/gpio38”
int main( int argc, char * argv[] )
{
FILE * fp;
int a=0;
fp = fopen( GPIO_PATH"/export","w");
if ( fp == NULL ) {
printf(“can not open file\n”);
return EXIT_FAILURE;
}
fprintf( fp, "38");
fclose( fp );
fp = fopen( GPIO38_PATH”/direction”, “w”);
if ( fp == NULL ) {
printf(“can not open file\n”);
return EXIT_FAILURE;
}
if(a==1)
fprintf( fp, “high”);
else fprintf( fp, “low”);
fclose(fp);
fp = fopen( GPIO38_PATH”/value”, “w”);
if ( fp == NULL ) {
printf(“can not open file\n”);
return EXIT_FAILURE;
}
fclose(fp);
}
Answer the question
In order to leave comments, you need to log in
I do not see a crime that could lead to a segfault in the above program.
Why behavior might differ between runs -- for example, because writing to a file /sys/class/gpio/export
changes the state of the system and is remembered between runs.
In addition, according to https://www.kernel.org/doc/Documentation/gpio/sysfs.txt , either should be direction
written in in
or out
, and high
or low
should be written in value
. Segfolta from this should not be, however.
What happens if you build a program with debug information and run it so that it crashes under the debugger?
UPD: I looked a little more... In the given source text, there are crooked Unicode quotes. I recommend correcting for ASCII, or inserting the source text as is, without tricks.
Try using a different pointer for the second file, or add a sleep between closing and opening.
Why the program crashes with SIGSEGV is also not entirely clear to me.
In the debugger, when an error occurs at the line fp = fopen( GPIO38_PATH”/direction”, “w”);
fp is 0 because of this, everything falls down for another time the result is normal
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question