marvinla wrote, On 04/07/07 15:00:
> Flash Gordon, thanks the reply!
Before anyone complains about lack of context, the post by marvinla does
actually stand on its own since it provides the full new code and a
statement of the problem.
> I rewrote my sample code, and my real code. Sorry for the dumbs
> mistakes.
Dumb mistakes we don't mind when people listen to the comments and
address them, which you seem to be doing, although you missed some of
the comments.
> But Valkyrie still warns me and my real code is still broken. Sorry
> for reposting all the code.
Posting your entire corrected code was the correct thing to do.
> #include <stdio.h>
> #include <stdlib.h>
>
> int main() {
It is better practice to be explicit about there being no parameters. It
does not make a difference here, but it is easier to always "do the
right thing" than to remember when you do not need to.
int main(void) {
>
> int i;
> int **p = malloc(2 * sizeof *p);
Check for p being a null pointer here, malloc can fail.
> for (i = 0; i < 2; i++)
> p[i] = malloc(2 * sizeof **p);
Check for p[i] being null here.
> p[0][0] = 0;
> p[0][1] = 1;
> p[1][0] = 2;
> p[1][1] = 3;
>
> printf("%d\n", p[0][0]);
> printf("%d\n", p[0][1]);
> printf("%d\n", p[1][0]);
> printf("%d\n", p[1][1]);
>
> p = realloc(p, 3);
In general you should not use realloc like this, since when it fails you
are throwing away your pointer to the still valid original block. You
should use a temp as in
tmp = realloc(p,newsize);
Not critical in this case since you terminate the program on failure,
but a point to remember for the future.
Now for your actual bug. What you wanted was, I believe,
p = realloc(p, 3 * sizeof *p);
As with malloc, realloc takes a number of bytes, not a number of objects
pointed to.
> if (p == NULL) {
> printf("OUT OF MEMORY!\n");
> exit(1);
1 is not a portable exit value, and under VMS it would actually be a
success code! You want
exit(EXIT_FAILURE);
<snip>
> I think I didn't understand the behavior of the realloc function
.
> Thanks a lot!
Correct, you don't. Both realloc and malloc take a number of bytes,
which is why I multiplied by the size of the object pointed to on my
malloc calls.
One last comment, please do not use tabs when posting. Sometimes they
seem to get lost, whether it is some peoples news clients, some peoples
posting software, or some news readers I can't be bothered to verify,
but it does happen. In any case, 8 characters is far too large an indent
level in my opinion.
--
Flash Gordon