malloc的使用?

C语言 码拜 9年前 (2015-05-11) 1066次浏览 0个评论
 

按照某课本写的栈,用函数malloc将预分配空间设置为1,为什么输入10个数字没有报错?

#include <iostream>
using namespace std;
#include <stdlib.h>

#define SInitSize 1
#define SizeIncrese 10
#define OVERFLOW 1

typedef  int SElemType ;
typedef int Status;

struct Stack
{
    SElemType *top;
    SElemType *base;
    int StackSize;
};

void InitStack(Stack &s)
{
    s.base=(SElemType *)malloc(SInitSize*sizeof(SElemType));
    if(!s.base)
        exit(OVERFLOW);
    s.top=s.base;
}

void Push(Stack &s, const SElemType e)
{
/*    if(s.top-s.base>=s.StackSize)
        s.base=(SElemType *)realloc(s.base,(s.StackSize+SizeIncrese)*sizeof(SElemType));
    if(!s.base)
        exit(OVERFLOW); */
    *s.top=e;
    ++s.top;
}

Status Pop(Stack &s, SElemType &e)
{
    if(s.top==s.base)
        return 0;
    --s.top;
    e=*s.top;
    return 1;
}

void Print(const Stack &s)
{
    SElemType *currptr=s.top;
    while(currptr!=s.base)
    {
        --currptr;
        cout<<*currptr<<"" "";

    }
}

int main()
{
    Stack s;
    InitStack(s);
    SElemType e;
    while(cin>>e)
        Push(s,e);
    Print(s);

    return 0;
}

malloc的使用?

3分
意外,不可依赖
2分
别写这种风格的代码..  C 不C  C++不C++的
溢出没报错是因为你颜值高,人品好
引用 楼主 liguanjun09050642 的回复:

按照某课本写的栈,用函数malloc将预分配空间设置为1,为什么输入10个数字没有报错?

#include <iostream>
using namespace std;
#include <stdlib.h>

#define SInitSize 1
#define SizeIncrese 10
#define OVERFLOW 1

typedef  int SElemType ;
typedef int Status;

struct Stack
{
    SElemType *top;
    SElemType *base;
    int StackSize;
};

void InitStack(Stack &s)
{
    s.base=(SElemType *)malloc(SInitSize*sizeof(SElemType));
    if(!s.base)
        exit(OVERFLOW);
    s.top=s.base;
}

void Push(Stack &s, const SElemType e)
{
/*    if(s.top-s.base>=s.StackSize)
        s.base=(SElemType *)realloc(s.base,(s.StackSize+SizeIncrese)*sizeof(SElemType));
    if(!s.base)
        exit(OVERFLOW); */
    *s.top=e;
    ++s.top;
}

Status Pop(Stack &s, SElemType &e)
{
    if(s.top==s.base)
        return 0;
    --s.top;
    e=*s.top;
    return 1;
}

void Print(const Stack &s)
{
    SElemType *currptr=s.top;
    while(currptr!=s.base)
    {
        --currptr;
        cout<<*currptr<<"" "";

    }
}

int main()
{
    Stack s;
    InitStack(s);
    SElemType e;
    while(cin>>e)
        Push(s,e);
    Print(s);

    return 0;
}

malloc的使用?

引用 1 楼 zhangxiangDavaid 的回复:

意外,不可依赖

引用 2 楼 dooX8086 的回复:

别写这种风格的代码..  C 不C  C++不C++的
溢出没报错是因为你颜值高,人品好

我是小白  

4分
不要违法操作,虽然不一定出事,但做多了,一定会出事。
6分
其实电脑开机后物理内存的每个字节都是可读写的,从来不会因为所谓的new、delete或malloc、free而被创建、销毁。区别仅在于操作系统内存管理模块在你读写时是否能发现并是否采取相应动作而已。操作系统管理内存的粒度不是字节而是页,一页通常为4KB。

借邻居家一分地种菜,为什么我刚才种了一亩,邻居家也没来人痛扁我呢?

5分
开车要求系安全带,但你想偷懒就是不系,结果开了几次发现没啥事,但反过来不能说明不系安全带就是正确的。对于你系不系安全带的问题,交警部门也不可能在每辆车启动时来检查你有没有系安全带。说的有点罗嗦,自己体会吧。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明malloc的使用?
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!