日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/3/21 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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("運行完成.");

}

結果也是你輸入值之后就提示

微信截圖_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

#include

#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;

}

數據類型不符合

這種情況下就是和第二種情況類似了。

總結

以上是生活随笔為你收集整理的c语言编写的程序停止运行程序,C语言中,编译成功但运行停止的几个原因的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。