Pebble 在 `realloc` 上崩溃,但仅在特定函数中崩溃

Pebble crashes on `realloc`, but only in a certain function

我在 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_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");
  }