0

刚才我用c写了一个简单的数据结构Sequence Stack,遇到了一个问题。

==8142== Use of uninitialised value of size 4
==8142==    at 0x408F4AB: _itoa_word (_itoa.c:195)
==8142==    by 0x40935EA: vfprintf (vfprintf.c:1629)
==8142==    by 0x4099EFE: printf (printf.c:35)
==8142==    by 0x40664D2: (below main) (libc-start.c:226)
==8142==  Uninitialised value was created by a heap allocation
==8142==    at 0x402BB7A: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==8142==    by 0x80484C9: sqstack_create (sqstack.c:24)
==8142==    by 0x80485D8: main (sqstack.c:84)
==8142== 
==8142== Conditional jump or move depends on uninitialised value(s)
==8142==    at 0x408F4B3: _itoa_word (_itoa.c:195)
==8142==    by 0x40935EA: vfprintf (vfprintf.c:1629)
==8142==    by 0x4099EFE: printf (printf.c:35)
==8142==    by 0x40664D2: (below main) (libc-start.c:226)
==8142==  Uninitialised value was created by a heap allocation
==8142==    at 0x402BB7A: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==8142==    by 0x80484C9: sqstack_create (sqstack.c:24)
==8142==    by 0x80485D8: main (sqstack.c:84)

结果显示第24行可能出现bug:

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

#include "status.h"

#define MAX_SIZE 10

typedef int ElemType;

typedef struct{
    ElemType *base;
    ElemType *top;
    int      size;
} sqstack_t;


sqstack_t *sqstack_create(){

    sqstack_t *s = (sqstack_t *)malloc(sizeof(sqstack_t));
    if (s == NULL) {
        return ERROR;
    }

    //this line  24
    s->base = (ElemType *)malloc(sizeof(ElemType)*MAX_SIZE);
    if (s->base == NULL) {
        return ERROR;
    }

    s->top = s->base;
    s->size = 0;

    return s;
}

Status sqstack_push(sqstack_t *s, ElemType data){

    if (s->size > MAX_SIZE) {
        printf("This stack is full!\n");
        return ERROR;
    }

    *s->top++ = data;
    s->size += 1;

    return OK;
}


ElemType sqstack_pop(sqstack_t *s){

    if (s->size == 0) {
        printf("This stack is empty!\n");
    return ERROR;
    }

    ElemType data;

    data = *s->top--;
    s->size -= 1;

    return data;
}


ElemType sqstack_top(sqstack_t *s){

    return *(s->top);
}


void sqstack_destroy(sqstack_t *s){

    s->top = NULL;
    free(s->base);
    free(s);
}

int main(void){

    sqstack_t *s;

    s = sqstack_create();

    sqstack_push(s, 10);
    sqstack_push(s, 20);
    sqstack_push(s, 30);
    sqstack_push(s, 40);

    printf("%d\n", sqstack_pop(s));
    printf("-%d-\n", sqstack_top(s));

    sqstack_destroy(s);

    return 0;
}

我不知道如何解决它。我是 C 新手,经常与内存分配和内存泄漏混淆。你能推荐我一些好的材料或书籍吗?

谢谢!

4

2 回答 2

1

使用这一行s->base = (ElemType *)malloc(sizeof(ElemType)*MAX_SIZE);,您正在分配内存,但它没有初始化并且具有随机值。所以访问s->base->somefield会产生随机值。

最好将其初始化为

memset(s->base, 0, sizeof(*(s->base)));

或使用calloc

s->base = (ElemType *)calloc(sizeof(ElemType)*MAX_SIZE, 1);
于 2013-05-23T11:03:10.237 回答
0

s->base是指向元素大小数组的指针MAX_SIZEElemType这些elemType不是初始化的。对该指针执行 memset 最MAX_SIZE多次。

于 2013-05-23T11:08:58.140 回答