簡體   English   中英

Geany錯誤代碼139:使用C的分段錯誤(核心已轉儲)

[英]Geany Error code 139: Segmentation fault (Core dumped) using C

我的整個程序會根據用戶輸入的文件名和模式創建一個新文件,然后檢查該文件是否存在。 之后,它輸出文件創建是否成功。 它應該很簡單,但是當我使用Geany編譯並成功構建並運行時,在終端窗口中會出現以下錯誤(但僅在進入模式“ r +”之后):

./geany_run_script.sh: line 5:  7395 Segmentation fault      (core dumped) "./test" c


------------------
(program exited with code: 139)
Press return to continue

然后我在讀完這篇文章后用gdb運行

分段故障(核心轉儲)

並得到此錯誤:

Program received signal SIGSEGV, Segmentation fault.
_IO_new_fclose (fp=0x0) at iofclose.c:54
54  iofclose.c: No such file or directory.

這是我的代碼:

#include <stdio.h>
#include <stdlib.h>

char filename[100];
char mode[2];

int main(int argc, char **argv)
{
    printf("Enter filename:\n>");
    scanf("%s", &*filename);
    printf("Select a mode from the list:\nr reading\nw writing\na append\nr+ reading &   writing (at beginning, overwriting)\nw+ reading & writing (overwrite on existing)\na+ reading & appending (new data appended at end of file)\n>");
    scanf("%s", &*mode);

    FILE * fp;
    fp = fopen(filename, mode);

    if (fp == NULL)
    {
        printf("Failed to open\n");
    }
    else
    {
        printf("Succesfully opened\n");
    }
    fclose(fp);

    return 0;
}

輸入文件名后出現gdb錯誤,這與Geany不同,后者在進入模式“ r +”后出現錯誤。

請幫助,並簡單地詢問您是否需要其他數據。 提前致謝。

編輯:我更新了代碼,以及有關何時出現錯誤的信息。 由於某種原因,它現在在程序中的不同點,具體取決於我是使用gdb還是使用Geany運行它。

文件模式需要兩個以上的字符:“ r +”等(NUL終止符)。 注意避免緩沖區溢出。

   char mode[3];
   fgets(mode, sizeof(mode), stdin);

並且fclose在未打開文件上的行為是不確定的。

if (fp == NULL) {
    printf("Failed to open\n");
} else {
    printf("Succesfully opened\n");
    fclose(fp); /* only close if fp != NULL, and only close once */
}

全部一起:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char **argv) {
    char filename[100];
    char mode[3];
    char *p;

    printf("Enter filename:\n>");
    fgets(filename, sizeof(filename), stdin);
    if ((p = strchr(filename, '\n')) != NULL) {
      *p = '\0'; /* remove any newline */
    }

    printf("Select a mode from the list:\n"
        "r reading\n"
        "w writing\n"
        "a append\n"
        "r+ reading & writing (at beginning, overwriting)\n"
        "w+ reading & writing (overwrite on existing)\n"
        "a+ reading & appending (new data appended at end of file)\n>");

    fgets(mode, sizeof(mode), stdin);
    if ((p = strchr(mode, '\n')) != NULL) {
      *p = '\0';
    }

    printf("opening %s with mode %s.\n", filename, mode);
    FILE *fp = fopen(filename, mode);

    if (fp == NULL) {
        printf("Failed to open\n");
    } else {
        printf("Succesfully opened\n");
        fclose(fp);
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM