Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

realloc help

Status
Not open for further replies.

nappaji

Programmer
Mar 21, 2001
76
US
The following code gives me a segmentation fault. I thinks its an issue with the syntax of realloc. Please advise.

#include <stdio.h>
#include <stdlib.h>

main()
{
int **arr;
int i,k, j;

arr = (int **) malloc (3);
arr[0] = (int *) malloc (2);
arr[1] = (int *) malloc (2);
arr[2] = (int *) malloc (2);

arr[0][0] = 9;
arr[0][1] = 21;

arr[1][0] = 44;
arr[1][1] = -9;

arr[2][0] = 12;
arr[2][1] = 22;

for (i=0;i<3;i++)
for (k=0;k<2;k++)
printf("\narr[%d][%d] = %d\n", i,k, arr[k]);

arr[0] = (int *) realloc (arr[0],(sizeof(arr[0]) + 1));

arr[0][2] = 234;

printf("\narr[0][2] = %d\n", arr[0][2]);
}
 
> arr = (int **) malloc (3);
1. Don't cast the result of malloc - doing so only hides a potential serious problem if you fail to include stdlib.h.
If your compiler is complaining about void* casts in C++, then stop compiling your code with a C++ compiler, and use a C compiler.

2. You're not allocating enough memory.
The template for using any malloc/realloc is as follows
[tt]T *ptr = malloc( num * sizeof *ptr );[/tt]
T is any type - say int
ptr is the name of your pointer, say arr
num is how many you want, say 3

So your first line would be
[tt]arr = malloc(3 * sizeof *arr);[/tt]


> arr[0] = (int *) realloc (arr[0],(sizeof(arr[0]) + 1));
sizeof() can't tell you how much memory you previously allocated. You need to save this in another variable, and adjust it accordingly.

Also, you're open to a memory leak using realloc in that way. If realloc fails, it returns NULL, but then you've lost your only handle to the memory you did have
This is how you should use realloc
Code:
void *temp = realloc( arr[0], (max+1)*sizeof(*arr[0]) );
if ( temp != NULL ) {
  // success, update max and our original pointer
  max += 1;
  arr[0] = temp;
} else {
  // oops, it failed
  // don't change max, and do something with arr[0]
  // which still points to the original memory we had
}

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top