问题
This is a homework assignment so I don't want to post any code, but I'm pretty stumped with the bug that I have.
Currently I have a array that has been malloced and am copying the pointer to the array. Now, I can memcpy and memmove with this array and that works fine.
However, when I do a realloc with it an invalid pointer error comes up - and I have absolutely no idea why.
Can anyone help?
回答1:
you said 'I copy the pointer to this array into another variable'. The problem is as soon as you do a realloc, the original pointer is no longer valid. I dont see the reason to copy the pointer to a variable?
回答2:
realloc()
only works if the pointer you pass it was one returned earlier from malloc()
, calloc()
or realloc()
(or is NULL
, in which case it works exactly like malloc()
).
You can not call it on arrays. If you have a struct
like this:
struct foo {
char a;
int x[5];
double z;
};
then you cannot use realloc()
to increase the size of x
. You must instead switch to using entirely dynamic allocation: the struct member changes to a pointer:
struct foo {
char a;
int *x;
double z;
};
...and when you create an instance of the struct
, you call malloc()
for the initial allocation:
struct foo f;
f.x = malloc(5 * sizeof f.x[0]);
Now you can call realloc()
on f.x
, but the cost is that you must also call free()
on f.x
when the struct is no longer needed.
回答3:
When realloc
or free
result in an invalid pointer error or segfault, and you are sure that you are passing a valid pointer obtained from malloc
, then a good possibility is that you corrupted your memory: You wrote to the area where malloc
stores the book keeping of the memory blocks. In your case this is a memcpy
or memmove
call.
You can use the valgrind memory error detector to help you find these kind of errors.
来源:https://stackoverflow.com/questions/7869757/realloc-invalid-pointer-in-c