我在Pebble应用程序中使用自定义向量。
Pebble在调用realloc
时崩溃了。
的main.c
#include <pebble.h>
#include "movement.h"
static PointArray point_array;
int main(void) {;
point_array_create(&point_array, 1);
GPoint point1 = (GPoint){.x = 1, .y = 1};
GPoint point2 = (GPoint){.x = 2, .y = 2};
GPoint point3 = (GPoint){.x = 3, .y = 3};
point_array_push(&point_array, point1);
point_array_push(&point_array, point2);
point_array_push(&point_array, point3);
APP_LOG(APP_LOG_LEVEL_DEBUG, "Done\n");
}
movement.c
#include "movement.h"
#include "pebble.h"
static void point_array_resize(PointArray *point_array){
point_array->capacity *= 2;
size_t new_size = point_array->capacity * sizeof(GPoint) + sizeof(GPoint);
point_array->points = (GPoint*)realloc(point_array->points, new_size);
}
void point_array_create(PointArray *arr, int capacity) {
arr->points = (GPoint*)malloc(capacity * sizeof(GPoint));
arr->length = 0;
arr->capacity = capacity;
}
void point_array_push(PointArray *point_array, GPoint point) {
APP_LOG(APP_LOG_LEVEL_DEBUG, "pushing");
if (point_array->length > point_array->capacity) {
APP_LOG(APP_LOG_LEVEL_DEBUG, "resizing");
point_array_resize(point_array);
APP_LOG(APP_LOG_LEVEL_DEBUG, "successful resize");
}
point_array->points[point_array->length] = point;
point_array->length++;
APP_LOG(APP_LOG_LEVEL_DEBUG, "+ length");
}
movement.h
#include <pebble.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
GPoint *points;
int length;
int capacity;
} PointArray;
void point_array_create(PointArray *arr, int capacity);
void point_array_push(PointArray *point_array, GPoint point);
void point_array_destroy(PointArray *point_array, GPoint point);
GPoint move(GPoint point, float distance, float degrees);
日志显示应用程序在调用realloc
时崩溃:
[DEBUG] movement.c:20: pushing
[DEBUG] movement.c:29: + length
[DEBUG] movement.c:20: pushing
[DEBUG] movement.c:29: + length
[DEBUG] movement.c:20: pushing
[DEBUG] movement.c:23: resizing
这是我试过的:
point_array
和point_array->points
不为空且new_size
大于point_array->points
的现有尺寸。realloc
的底部调用point_array_create
,它运行正常。它只是在point_array_resize
。答案 0 :(得分:3)
在point_array_push
中,您测试是否需要调整顶部的点数,但测试是错误的。只有在长度超出容量时才会调整大小,这意味着您已经超出了阵列。
相反,请检查长度是否已达到容量。
if (point_array->length == point_array->capacity) {
APP_LOG(APP_LOG_LEVEL_DEBUG, "resizing");
point_array_resize(point_array);
APP_LOG(APP_LOG_LEVEL_DEBUG, "successful resize");
}