繁体   English   中英

Leetcode : AddressSanitizer 堆缓冲区溢出

[英]Leetcode : AddressSanitizer heap-buffer-overflow

我正在练习 Leetcode 问题“链表中的下一个更大的节点”,这是我的代码:

#define STACK_SIZE (10000U)

typedef struct ListNode Node;

static int stack[STACK_SIZE];
static int top=-1;

bool isEmpty()
{
    return (top==-1);
}

void addToStack(int element)
{
    stack[++top]=element;
}

void remFromStack()
{
    --top;    
}

int getStackTop()
{
    return stack[top];
}

 typedef struct ListNode Node;

 int* nextLargerNodes(struct ListNode* head, int* returnSize) {

        if (head == NULL) {

            *returnSize = 0;
            return NULL;
        }

        int len = 0;
        Node *temp = head;

        while (temp) {
            len++;
            temp = temp->next;
        }

        if (len > 0) {
            int *result = malloc(len * sizeof(int));
            *returnSize = len;

            if (result == NULL) {
                return NULL;
            }

            int j = 0;
            while (j < len) {
                result[j++] = 0;
            }

            temp = head;
            addToStack(temp->val);
            j = 0;
            while (temp->next) {
                temp = temp->next;
                j++;

                if (getStackTop() > temp->val) {
                    addToStack(temp->val);
                } else {
                    int i = 0;
                    while (!isEmpty()) {
                        i++;
                        result[j - i] = temp->val;
                        remFromStack();
                    }
                    addToStack(temp->val);
                }
            }
            return result;
        } else {
            return NULL;
        }

}

我收到以下错误:

=================================================================
==29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6030000
WRITE of size 4 at 0x60300000000c thread T0
 #2 0x7f55143382e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.s
0x60300000000c is located 4 bytes to the left of 20-byte region [0x60300
allocated by thread T0 here:
 #0 0x7f55157c22b0 in malloc (/usr/local/lib64/libasan.so.5+0xe82b0)
 #3 0x7f55143382e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.s

我不确定这里出了什么问题。

尝试确保所有代码都是正确的,当我针对自己的测试用例测试代码时,它工作得非常好,但是当我提交代码时,才出现此错误。

注意:返回的数组必须被malloced,假设调用者调用free()。

实用程序函数中没有调用任何 malloc/calloc,因此,将它们从等式中删除。

Sizeof 在 Leetcode 上的表现不同。

尝试使用 strlen(如果您使用 char)或其他方法来查找您尝试使用的数据类型的大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM