我正在练习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)或其他方法来查找您尝试使用的数据类型的大小。
关于c - 力扣 : AddressSanitizer heap-buffer-overflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56095356/