VC6編譯代碼時一種常見錯誤解決

來源:互聯網
上載者:User

  今天跑程式就實現了一個棧,寫了個動態分配空間的代碼,代碼看來看去,都沒發現問題,但是運行過程中卻出問題了。

   以下是糾正錯誤前的代碼,也許是我不夠細心,代碼寫的不夠完善,但是咋看還是看不出啥問題的,大家也來看看。

   錯誤碼如下:

#include "stdio.h"#include "stdlib.h"#include "string.h"#define INIT_SIZE 100#define INCREMENT 10#define OK 1#define ERROR 0typedef  int Status;typedef  int SElemType;typedef struct Stack{SElemType *base;SElemType *top;int stackSize;}MyStack;Status initStack(MyStack *p){p->base = (SElemType *)malloc(sizeof(SElemType)*INIT_SIZE);if(p->base == NULL){return ERROR;}p->top=p->base;p->stackSize = INIT_SIZE;return OK;}/*getTop is not pop .*/Status getTop(MyStack p,SElemType *e){if(p.base == p.top){return ERROR;}*e=*(p.top-1);return OK;}Status push(MyStack *p,SElemType e){if(p->top-p->base>=p->stackSize){p->base = (SElemType *)realloc(p->base,sizeof(SElemType)*(INIT_SIZE+INCREMENT));if(p->base == NULL){return ERROR;}p->top = p->base + p->stackSize;p->stackSize = p->stackSize+INCREMENT;}*p->top++ = e;return OK;}Status pop(MyStack *p,SElemType *e){if(p->top == p->base){return ERROR;}*e = *(--p->top);return OK;}Status destroy(MyStack *p){if(p->base != NULL){free(p->base);}p->stackSize =0;p->top=NULL;return OK;}int main(){MyStack *my;int e;initStack(my);push(my,1);push(my,2);push(my,3);pop(my,&e);printf("%d ",e);pop(my,&e);printf("%d ",e);pop(my,&e);printf("%d ",e);destroy(my);return 0;}

編譯過程中出現如下問題:

Loaded 'ntdll.dll', no matching symbolic information found.
Loaded 'C:\WINDOWS\system32\kernel32.dll', no matching symbolic information found.

Unhandled  exception in stack.exe:0xC0000005: Access Violation

通過分析可知這是記憶體訪問越界的問題,應該編譯器到某一個不知道的地方,去尋找相應的變數,這裡

MyStack *my;

是一個未配置的空間的指標,不能確定指標位置,因此如果我使用該指標的成員來分配空間,我就無法確定該空間分配在什麼位置。就會找出記憶體訪問越界的嚴重問題,可見一個小小的疏忽竟造成如此大的問題。

修改代碼如下:

int main(){MyStack *my;int e;my =(MyStack *)malloc(sizeof(MyStack));initStack(my);push(my,1);push(my,2);push(my,3);pop(my,&e);printf("%d ",e);pop(my,&e);printf("%d ",e);pop(my,&e);printf("%d ",e);destroy(my);free(my);return 0;}

解決問題的方法,就是分配空間。有些時候編程時,注重邏輯結構的完整,忽視了一些細節,這樣一些簡單的問題,往往會困擾我們碼農。因此以後再編程中遇到需要動態分配空間以及釋放的問題,多留心多注意,把它當成一種習慣,這樣可以減少不必要的低級錯誤。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.