简体   繁体   中英

segmentation fault in a C code

I have written a C code yesterday which works fine. Now I want to make some changes in the file, so I just copy this code in a new file. Compilation of new file is just fine, but when I try to run my executable file, I am getting segmentation fault . However my previous code is working. Initially I thought it's a permission issue so I change the permission of executable using chmod 777 . But still I am getting segmentation fault . Here is my code:-

#include <stdio.h>
#include <time.h>
void pauseSec(int sec);
int main() {
        FILE *io,*iodir,*ioval,*iodir_S,*ioval_S,*io_S,*iodir_P,*ioval_P,*io_P;

        io = fopen("/sys/class/gpio/export", "w");
        fseek(io,0,SEEK_SET);
        fprintf(io,"%d",15);
        fflush(io);
        iodir = fopen("/sys/class/gpio/gpio15/direction", "w");
        fseek(iodir,0,SEEK_SET);
        fprintf(iodir,"out");
        fflush(iodir);
        while(1)
        {
                fprintf(ioval,"%d",1);
                fflush(ioval);
                pauseSec(1);
                fprintf(ioval,"%d",0);
                fflush(ioval);
                pauseSec(1);
        }
        fclose(io);
        fclose(iodir);
        fclose(ioval);
        return 0;
}
void pauseSec(int sec) {
        time_t now,later;
        now = time(NULL);
        later = time(NULL);
        while((later - now) < (double)sec)
        later = time(NULL);
}

I wonder why same code is behaving differently when written in two different file. What can be the reason for this?

Got the issue, forget to initialize ioval . Correct code is here:-

#include <stdio.h>
#include <time.h>
void pauseSec(int sec);
int main() {
        FILE *io,*iodir,*ioval,*iodir_S,*ioval_S,*io_S,*iodir_P,*ioval_P,*io_P;

        io = fopen("/sys/class/gpio/export", "w");
        fseek(io,0,SEEK_SET);
        fprintf(io,"%d",15);
        fflush(io);

        iodir = fopen("/sys/class/gpio/gpio15/direction", "w");
        fseek(iodir,0,SEEK_SET);
        fprintf(iodir,"out");
        fflush(iodir);

        ioval = fopen("/sys/class/gpio/gpio15/value", "w");

        while(1)
        {
                fprintf(ioval,"%d",1);
                fflush(ioval);
                pauseSec(1);
                fprintf(ioval,"%d",0);
                fflush(ioval);
                pauseSec(1);
        }
        fclose(io);
        fclose(iodir);
        fclose(ioval);
        return 0;
}
void pauseSec(int sec) {
        time_t now,later;
        now = time(NULL);
        later = time(NULL);
        while((later - now) < (double)sec)
        later = time(NULL);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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