473,465 Members | 1,570 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Problem with passing dynamic arrays by reference

Hi!

Sorry for the weird topic, I don't know how to describe it better...
I have a little problem here I can't wrap my mind around. If I do:

-------------------------------------
#define DWORD unsigned long
#include <stdio.h>
#include <malloc.h>

int main(int argc, char* argv[])
{
DWORD *arr;
int i;

arr = malloc(sizeof(DWORD));
arr[0] = 1;
arr = realloc(arr,2*sizeof(DWORD));
arr[1] = 2;
for(i=0;i<=1;i++)
{
printf("%d\n",arr[i]);
}
}
-------------------------------------

This works just fine, as expected. But when I try to do the allocation
and assignment inside a function, I get some (to me) strange behaviour.

-------------------------------------
#define DWORD unsigned long
#include <stdio.h>
#include <malloc.h>

void func(DWORD **arr)
{
*arr = malloc(sizeof(DWORD));
*arr[0] = 1;
*arr = realloc(*arr,2*sizeof(DWORD));
// crash here, as if trying to write to a bad ptr location
*arr[1] = 2;
}

int main(int argc, char* argv[])
{
DWORD *arr;
int i;

func(&arr);
for(i=0;i<=2;i++)
{
printf("%d\n",arr[i]);
}
}
-------------------------------------

I'm sure it's quite easy and I just don't see it, but I just can't
figure out whats wrong with the code above. Can someone help me please?

Thanks,

Thomas

P.S.: Yes, I normally check for return values of malloc and realloc, I just
left it out of the post for brevity ;-)
Nov 14 '05 #1
3 2064
Thomas Christmann <th***************@online.de> scribbled the following:
Hi! Sorry for the weird topic, I don't know how to describe it better...
I have a little problem here I can't wrap my mind around. If I do: -------------------------------------
#define DWORD unsigned long
#include <stdio.h>
#include <malloc.h>
<malloc.h> is a non-standard header and not needed in your entire
program. Use <stdlib.h> instead.
int main(int argc, char* argv[])
{
DWORD *arr;
int i;

arr = malloc(sizeof(DWORD));
arr[0] = 1;
arr = realloc(arr,2*sizeof(DWORD));
This is dangerous. If realloc() fails to allocate more memory, it
keeps the original memory intact but returns NULL. You then end up
overwriting your previous pointer with NULL, which means both that
you've lost touch with your memory and the next line will cause
undefined behaviour.
Try this instead:
DWORD *arr, *tmp;
arr = malloc(sizeof(DWORD));
tmp = realloc(arr,2*sizeof(DWORD));
if (tmp != NULL) {
arr = tmp;
}
arr[1] = 2;
for(i=0;i<=1;i++)
{
printf("%d\n",arr[i]);
}
}
------------------------------------- This works just fine, as expected. But when I try to do the allocation
and assignment inside a function, I get some (to me) strange behaviour. -------------------------------------
#define DWORD unsigned long
#include <stdio.h>
#include <malloc.h>
The same comments as above apply here.
I note with interest that you appear to have got the pointer-to-pointer
passing in the function right. This may surprise you, but many newbies
get it wrong on the first try, thinking that assigning to a parameter
changes the value of the original variable, as long as that parameter's
type is a pointer. You, however, are correctly assigning to what the
pointer parameter points to.
void func(DWORD **arr)
{
*arr = malloc(sizeof(DWORD));
*arr[0] = 1;
*arr = realloc(*arr,2*sizeof(DWORD));
// crash here, as if trying to write to a bad ptr location
Please also check if realloc() returns null here.
*arr[1] = 2;
I'm not too sharp on the C parsing rules, but I have a sneaky
suspicion that this is parsed as *(arr[1]) = 2, which will quite
obviously fail. Most likely if I'm wrong, Dan Pop will now tell me
to engage my brain and actually learn C. Just to be on the safe
side, try (*arr)[1] = 2.
} int main(int argc, char* argv[])
{
DWORD *arr;
int i;

func(&arr);
for(i=0;i<=2;i++)
{
printf("%d\n",arr[i]);
}
}
------------------------------------- I'm sure it's quite easy and I just don't see it, but I just can't
figure out whats wrong with the code above. Can someone help me please? Thanks, Thomas P.S.: Yes, I normally check for return values of malloc and realloc, I just
left it out of the post for brevity ;-)


--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"The large yellow ships hung in the sky in exactly the same way that bricks
don't."
- Douglas Adams
Nov 14 '05 #2


Thomas Christmann wrote:
But when I try to do the allocation
and assignment inside a function, I get some (to me) strange behaviour.

-------------------------------------
#define DWORD unsigned long
#include <stdio.h>
#include <malloc.h>

void func(DWORD **arr)
{
*arr = malloc(sizeof(DWORD));
*arr[0] = 1;
*arr = realloc(*arr,2*sizeof(DWORD));
// crash here, as if trying to write to a bad ptr location
*arr[1] = 2;
}
Other(s) have described the cause of your chief compliant. It
is a precedence and order of evaluation problem that is solved by
changing:
*arr[0] = 1;
to
(*arr)[0] = 1;
and changing:
*arr[1] = 2;
to
(*arr)[1] = 2;
int main(int argc, char* argv[])
{
DWORD *arr;
int i;

func(&arr);
for(i=0;i<=2;i++)
{
printf("%d\n",arr[i]);
By the way, with printf, the correct specifier for
unsigned long, (DWORD), is %lu not %d.
}
}
-------------------------------------

I'm sure it's quite easy and I just don't see it, but I just can't
figure out whats wrong with the code above. Can someone help me please?

Thanks,

Thomas

P.S.: Yes, I normally check for return values of malloc and realloc, I just
left it out of the post for brevity ;-)


--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #3
Thomas Christmann wrote:
... But when I try to do the allocation
and assignment inside a function, I get some (to me) strange behaviour. #define DWORD unsigned long
#include <stdio.h>
#include <malloc.h> void func(DWORD **arr)
{
*arr = malloc(sizeof(DWORD));
*arr[0] = 1;
*arr = realloc(*arr,2*sizeof(DWORD));
// crash here, as if trying to write to a bad ptr location
*arr[1] = 2;
} int main(int argc, char* argv[])
{
DWORD *arr;
int i;

func(&arr);
for(i=0;i<=2;i++)
{
printf("%d\n",arr[i]);
}
} I'm sure it's quite easy and I just don't see it, but I just can't
figure out whats wrong with the code above. Can someone help me please?


Note the output for the locations:

#include <stdio.h>
#include <stdlib.h> /* mha: was <malloc.h> */

void func(unsigned long **arr)
{
unsigned long *tmp;
*arr = malloc(sizeof(unsigned long));
*arr[0] = 1;
tmp = realloc(*arr, 2 * sizeof(unsigned long));
if (tmp)
*arr = tmp;
/* mha: a poor way to handle error, but WTF */
else {
*arr = 0;
return;
}
(*arr)[1] = 2; /* mha: was '*arr[1] = 2;/ */
printf("value of *arr %p\n" "address of (*arr[1]) %p\n"
"address of ((*arr)[1]) %p\n", (void *) (*arr),
(void *) &(*arr[1]), (void *) &((*arr)[1]));
}

int main(void)
{
unsigned long *arr;
int i;

func(&arr);
if (arr)
for (i = 0; i <= 2; i++)
printf("%ld\n", arr[i]); /* mha: changed "%d" to "%ld" */
return 0;
}

Nov 14 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: harry | last post by:
I have 2 multi-dim arrays double subTotals = null; String rowTitles = null; I want to pass them to a function that initialises & populates them like so - loadData( rowTitles, subTotals);
58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
4
by: Scott Lyons | last post by:
Hey all, Can someone help me figure out how to pass a dynamic array into a function? Its been giving me some trouble, and my textbook of course doesnt cover the issue. Its probably something...
2
by: NM | last post by:
Hello all, I am supposed to do some mixed programming with c++ and fortran. I was succeeful in exchanging the 2D arrays from fortran to c++ and the other way, but was unable to that same with...
11
by: John Pass | last post by:
Hi, In the attached example, I do understand that the references are not changed if an array is passed by Val. What I do not understand is the result of line 99 (If one can find this by line...
2
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c...
11
by: toton | last post by:
Hi, I have little confusion about static memory allocation & dynamic allocation for a cluss member. I have class like class Bar{ public: explicit Bar(){ cout<<"bar default"<<endl; }
11
by: venkatagmail | last post by:
I have problem understanding pass by value and pass by reference and want to how how they are or appear in the memory: I had to get my basics right again. I create an array and try all possible...
7
by: Nates | last post by:
I have built a quote engine for the rating of insurance premiums. Each month the rates that generate the premiums change which requires a new database file be created with updated premium tables (we...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.