C语言中,编译成功但运行停止的几个原因

参考文章-C语言里程序编译无误但运行会弹出程序已停止运行是为什么

背景导入

《C语言中,编译成功但运行停止的几个原因》 微信截图_20180428165124.png

是否有过这样的经历的,当你兴致满满的编译好你的C文件后,运行的时候却出现了这样子的惨痛经历。下面,我将总结几种出现这种问题的原因。

栈区过大

# include "stdio.h"
int main(){
    int MB[209715200000];
    printf("allocate the memory successfully!");
    return 0;
}

当然,为了效果明显,我们故意将只分配弄得特别大,所以这里,我们运行一下可以看到:

$gcc -o main *.c
$main
timeout: the monitored command dumped core
sh: line 1: 72469 Segmentation fault      timeout 10s main

错误地址访问

指针偏移

# include "stdio.h"
int main(){
    int x;
    scanf("%d", x);
    printf("运行完成.");
}

结果也是你输入值之后就提示
《C语言中,编译成功但运行停止的几个原因》 微信截图_20180428165124.png

#include "time.h"
#include "stdio.h"
#include "string.h"
char *asctime2(const struct tm *timer){
    const char wday_name[7][3] = {
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
    };
    const char mon_name[12][3] = {
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    };
    static char result[50];  // 用于储存字符串的空间是静态空间

// this is a wrong vison which can cause the program to stop accidently
    sprintf(result, "%.3s %.3s %02d %02d:%02d:%02d %4d", 
        wday_name[timer->tm_wday],
        mon_name[timer->tm_mon,
        timer->tm_mday,
        timer->tm_hour,
        timer->tm_min,
        timer->tm_sec,
        timer->tm_year + 1900]);
return result;
}

int main(){
    time_t current;
    time(&current);
    struct tm *timer;
    timer = localtime(&current);
    char x[100];
    strcpy(x, asctime2(timer));
    printf("%s\n", x);
    return 0;
}

上面这段程序,同样也会报错,而我们认真观察可以看到,在sprintf()的参数中,我们由于码字的时候,把]的位置直接放在了最后面,但这里,编译器并不会报错,而是任其肆意妄为。
而正确的代码应该如下:

sprintf(result, "%.3s %.3s %02d %02d:%02d:%02d %4d", 
        wday_name[timer->tm_wday],
        mon_name[timer->tm_mon],
        timer->tm_mday,
        timer->tm_hour,
        timer->tm_min,
        timer->tm_sec,
        timer->tm_year + 1900);

指针未初始化就使用了

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

#define STACK_INIT_SIZE 100
#define SINCREASEMENT 10

typedef int ElemType;

typedef struct stack
{
    ElemType *base;
    ElemType *top;
    int stack_size;
}stack, *ListStack;

void init(ListStack S){
    // 分配空间
    printf("3\n");
    S -> base = malloc(STACK_INIT_SIZE*sizeof(ElemType));
    printf("2\n");
    if (!S->base){
        exit(1);  // 分配空间失败
    }
    printf("1\n");
    S -> top = S -> base;
    S -> stack_size = STACK_INIT_SIZE;
}

int main(){
    ListStack Lstack;   // 这里的指针是野指针,指向哪里谁也不知道,所以运行时会报错
    init(Lstack);

    return 0;
}

这里main函数应该写作

int main(){
    stack Lstack;
    init(&Lstack);
    return 0;
}

数据类型不符合

这种情况下就是和第二种情况类似了。

    原文作者:obsession_me
    原文地址: https://www.jianshu.com/p/3ab5e5d59a0b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞