473,322 Members | 1,259 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

allocate memory for pointer

I encountered "segmentation fault" and I checked my code, found the
following problem:

I want to reallocate memory for an array.
I defined the following function:

int reallocateMemory( double *array, int newsize )
{
if (array) delete[] array;

array = new double[newsize];

return 1;
}

Now,
int main()
{
double *a = new double[2], *b = new double[10];

cout << a << endl; // address of a. (1)

for ( int i = 0; i < 10; i++ ) b[i] = i; // b = {0,1,....,9}

reallocateMemory( a, 10 );

cout << a << endl; // the address of a is same as (1)! :(

for ( int i = 0; i < 10; i++ ) a[i] = 0.1*i;

for ( int i = 0; i < 10; i++ )
cout << a[i] << " ";
cout << endl; // fine, a is 0,0.1,...,0.9

for ( int i = 0; i < 10; i++ )
cout << b[i] << " ";
cout << endl;

// error: output = 0.3,0.4,...,0.9,7,8,9

return 0;
}

So the memory of "a" is not reallocated although I call the function to
change it.

What I think is that passed-by-pointer in function will change the
parameter directly. Therefore after I call the function
reallocateMemory, "a" should be changed. But it seems that the result is
same as passed-by-value.

What's the problem in my function?

Thank you for your help!

X
Jul 22 '05 #1
13 2455

"xuatla" <xu****@gmail.com> wrote in message
news:40**************@gmail.com...
I encountered "segmentation fault" and I checked my code, found the
following problem:

I want to reallocate memory for an array.
I defined the following function:

int reallocateMemory( double *array, int newsize )
{
if (array) delete[] array;

array = new double[newsize];
How do you return array back to main now?
return 1;
}

Now,
int main()
{
double *a = new double[2], *b = new double[10];

cout << a << endl; // address of a. (1)

for ( int i = 0; i < 10; i++ ) b[i] = i; // b = {0,1,....,9}

reallocateMemory( a, 10 );


After this function a points to deleted memory. Henceforth trying anything
on that memory is UB.

So it resolve the problem change reallocate to -
int reallocateMemory( double *&array, int newsize )
^^^^^^^^
You are now paasing a reference to a pointer. Any changes now made to array
will be reflected back in main.

-Sharad

Jul 22 '05 #2
On Thu, 15 Jul 2004 00:20:39 -0700, xuatla <xu****@gmail.com> wrote:
I encountered "segmentation fault" and I checked my code, found the
following problem:

I want to reallocate memory for an array.
I defined the following function:

int reallocateMemory( double *array, int newsize )
{
if (array) delete[] array;

array = new double[newsize];

return 1;
}

Now,
int main()
{
double *a = new double[2], *b = new double[10];

cout << a << endl; // address of a. (1)

for ( int i = 0; i < 10; i++ ) b[i] = i; // b = {0,1,....,9}

reallocateMemory( a, 10 );

cout << a << endl; // the address of a is same as (1)! :(

for ( int i = 0; i < 10; i++ ) a[i] = 0.1*i;

for ( int i = 0; i < 10; i++ )
cout << a[i] << " ";
cout << endl; // fine, a is 0,0.1,...,0.9

for ( int i = 0; i < 10; i++ )
cout << b[i] << " ";
cout << endl;

// error: output = 0.3,0.4,...,0.9,7,8,9

return 0;
}

So the memory of "a" is not reallocated although I call the function to
change it.

What I think is that passed-by-pointer in function will change the
parameter directly. Therefore after I call the function
reallocateMemory, "a" should be changed. But it seems that the result is
same as passed-by-value.
Yes, pointers are passed by value just like everything else.

What's the problem in my function?


You are passing by value. If you want to use a function to change that
value of a variable you have three alternatives.

1) Use a return value

double* reallocateMemory( double *array, int newsize )
{
delete[] array;
return new double[newsize];
}

a = reallocateMemory( a, 10 );

2) Use a reference

void reallocateMemory( double*& array, int newsize )
{
delete[] array;
array = new double[newsize];
}

reallocateMemory( a, 10 );

3) Use a pointer (in your case this would be a pointer to a pointer)

void reallocateMemory( double** array, int newsize )
{
delete[] *array;
*array = new double[newsize];
}

reallocateMemory( &a, 10 );
BTW it is not necessary to test for NULL before deleteing a pointer

if (ptr) delete[] ptr;

works exactly the same as

delete[] ptr;

Deleting NULL is guaranteed to have no effect.

john
Jul 22 '05 #3
[...]
int reallocateMemory( double *array, int newsize )
{
if (array) delete[] array;

array = new double[newsize];

return 1;
} [...]
What's the problem in my function?

your function changes only the local variable array which has no
influence to your variable a in main. Changing the functiondeclaration to
int reallocateMemory( double *&array, int newsize )
should do the trick. Now not the value of a is passed to the function
but the reference of it so you're able to modify its value...

Jul 22 '05 #4
Thanks all of you for the kind help.

I made a mistake. As I mentioned I thought passed-by-pointer is
different with passed-by-value and the change will be kept after calling
the function. Now I know I made a mistake. If "a" is a double value, not
an array, then

testfun( double *a)
{ *a = newvalue; }
and
{
...
double a;
testfun(&a);
}
will change the value of a. But what I used is the pointer to an array.
So it's differnt.

Thanks for pointing out my mistake and giving me the good answers.

I have one more related (and naive) question
(1) double* a --- a is a double array
(2) double *a --- a is a double pointer

what's the difference of (1) & (2)? both a are address and one points to
an array while another points to a value. is there any other characters
in expression tell c++ that there're different? Thanks!

X

John Harrison wrote:
On Thu, 15 Jul 2004 00:20:39 -0700, xuatla <xu****@gmail.com> wrote:
I encountered "segmentation fault" and I checked my code, found the
following problem:

I want to reallocate memory for an array.
I defined the following function:

int reallocateMemory( double *array, int newsize )
{
if (array) delete[] array;

array = new double[newsize];

return 1;
}

Now,
int main()
{
double *a = new double[2], *b = new double[10];

cout << a << endl; // address of a. (1)

for ( int i = 0; i < 10; i++ ) b[i] = i; // b = {0,1,....,9}

reallocateMemory( a, 10 );

cout << a << endl; // the address of a is same as (1)! :(

for ( int i = 0; i < 10; i++ ) a[i] = 0.1*i;

for ( int i = 0; i < 10; i++ )
cout << a[i] << " ";
cout << endl; // fine, a is 0,0.1,...,0.9

for ( int i = 0; i < 10; i++ )
cout << b[i] << " ";
cout << endl;

// error: output = 0.3,0.4,...,0.9,7,8,9

return 0;
}

So the memory of "a" is not reallocated although I call the function
to change it.

What I think is that passed-by-pointer in function will change the
parameter directly. Therefore after I call the function
reallocateMemory, "a" should be changed. But it seems that the result
is same as passed-by-value.

Yes, pointers are passed by value just like everything else.

What's the problem in my function?


You are passing by value. If you want to use a function to change that
value of a variable you have three alternatives.

1) Use a return value

double* reallocateMemory( double *array, int newsize )
{
delete[] array;
return new double[newsize];
}

a = reallocateMemory( a, 10 );

2) Use a reference

void reallocateMemory( double*& array, int newsize )
{
delete[] array;
array = new double[newsize];
}

reallocateMemory( a, 10 );

3) Use a pointer (in your case this would be a pointer to a pointer)

void reallocateMemory( double** array, int newsize )
{
delete[] *array;
*array = new double[newsize];
}

reallocateMemory( &a, 10 );
BTW it is not necessary to test for NULL before deleteing a pointer

if (ptr) delete[] ptr;

works exactly the same as

delete[] ptr;

Deleting NULL is guaranteed to have no effect.

john

Jul 22 '05 #5

"xuatla" <xu****@gmail.com> wrote in message
news:40**************@gmail.com...
I have one more related (and naive) question
(1) double* a --- a is a double array
(2) double *a --- a is a double pointer


No both are pointers.
double* a, b;
a is a pointer to double while b is a double.
Arrays are indicated by the subscript operator [] like arr[10] . Arrays
decay down to pointers though.

-Sharad

Jul 22 '05 #6

"xuatla" <xu****@gmail.com> wrote in message
news:40**************@gmail.com...
Thanks all of you for the kind help.

I made a mistake. As I mentioned I thought passed-by-pointer is
different with passed-by-value and the change will be kept after calling
the function. Now I know I made a mistake. If "a" is a double value, not
an array, then

testfun( double *a)
{ *a = newvalue; }
and
{
...
double a;
testfun(&a);
}
will change the value of a. But what I used is the pointer to an array.
So it's differnt.

Thanks for pointing out my mistake and giving me the good answers.

I have one more related (and naive) question
(1) double* a --- a is a double array
(2) double *a --- a is a double pointer

what's the difference of (1) & (2)?
There is no difference at all. Whitespace is not significant in C++. Some
people say that stylistically 2 is better than 1 and a few say the opposite,
but that's all it is, a style issue.
both a are address and one points to
an array while another points to a value. is there any other characters
in expression tell c++ that there're different? Thanks!


Both are pointers. Strictly speaking if you want a pointer to an array its a
different syntax

int a[5] = { 1, 2, 3, 4, 5 };
int (*p)[5] = &a; // a pointer to an array
cout << (*p)[0]; // prints 1

but true pointers to arrays are not used very much, so people often say
pointer to an array when really they mean a pointer which happens to be
pointing to the first element of an array.

int a[5] = { 1, 2, 3, 4, 5 };
int *p = a; // a pointer which is pointing to the first element of a
cout << *p; // prints 1

john
Jul 22 '05 #7
John Harrison posted:

"xuatla" <xu****@gmail.com> wrote in message
news:40**************@gmail.com...
Thanks all of you for the kind help.

I made a mistake. As I mentioned I thought passed-by- pointer is different with passed-by-value and the change will be kept after calling the function. Now I know I made a mistake. If "a" is a double value, not an array, then

testfun( double *a)
{ *a = newvalue; } and { ...
double a;
testfun(&a);
}
will change the value of a. But what I used is the pointer to an array. So it's differnt.

Thanks for pointing out my mistake and giving me the good answers.
I have one more related (and naive) question
(1) double* a --- a is a double array
(2) double *a --- a is a double pointer

what's the difference of (1) & (2)?
There is no difference at all. Whitespace is not

significant in C++. Some people say that stylistically 2 is better than 1 and a few say the opposite, but that's all it is, a style issue.
both a are address and one points to
an array while another points to a value. is there any other characters in expression tell c++ that there're different? Thanks!
Both are pointers. Strictly speaking if you want a

pointer to an array its a different syntax

int a[5] = { 1, 2, 3, 4, 5 };
int (*p)[5] = &a; // a pointer to an array
cout << (*p)[0]; // prints 1

but true pointers to arrays are not used very much, so people often say pointer to an array when really they mean a pointer which happens to be pointing to the first element of an array.

int a[5] = { 1, 2, 3, 4, 5 };
int *p = a; // a pointer which is pointing to the first element of a cout << *p; // prints 1

john


The following is a mess. What I tried to get was a
multidemensional array with new.

It compiles, but don't ask me what it does. Note how at one
point I've write int[5][5][5][5], as opposed to just three
5's, it won't compile otherwise and I don't know why.

Anyway,
#ifndef INCLUDE_ACCESSOR_CAST
#define INCLUDE_ACCESSOR_CAST

template<typename TO, class FROM>
inline TO& accessor_cast(FROM& from)
{
return *(reinterpret_cast<TO*>(&from));
}

template<typename TO, class FROM>
inline const TO& accessor_cast(const FROM& from)
{
return *(reinterpret_cast<const TO*>(&from));
}

#endif
int main()
{
int* blah = new int[125];

int (*krt)[5][5][5] = accessor_cast<int([5][5][5][5])>
(blah);

*krt[1][3][2] = 45;

delete [] blah;
}
-JKop
Jul 22 '05 #8
>
The following is a mess. What I tried to get was a
multidemensional array with new.

It compiles, but don't ask me what it does. Note how at one
point I've write int[5][5][5][5], as opposed to just three
5's, it won't compile otherwise and I don't know why.

Anyway,
#ifndef INCLUDE_ACCESSOR_CAST
#define INCLUDE_ACCESSOR_CAST

template<typename TO, class FROM>
inline TO& accessor_cast(FROM& from)
{
return *(reinterpret_cast<TO*>(&from));
}

template<typename TO, class FROM>
inline const TO& accessor_cast(const FROM& from)
{
return *(reinterpret_cast<const TO*>(&from));
}

#endif
int main()
{
int* blah = new int[125];

int (*krt)[5][5][5] = accessor_cast<int([5][5][5][5])>
(blah);

*krt[1][3][2] = 45;

delete [] blah;
}


int[5][5][5][5] has 625 elements and your original array has 125. I think
you meant this

int main()
{
int* blah = new int[125];
int (*krt)[5][5] = accessor_cast<int[5][5][5]> (blah);

krt[1][3][2] = 45;
delete [] blah;
}

It just an example of an array to pointer conversion. int[5][5][5] is an
array of size 5, where each element happens to be an int[5][5]. Therefore
int[5][5][5] can convert to a pointer to int[5][5]. The syntax for pointer
to int[5][5] is int (*)[5][5].

Another way of writing your cast would be

int (*krt)[5][5] = accessor_cast<int(*)[5][5]> (blah);

Nothing was compiled so apologies in advance for any stupid mistakes.

john
Jul 22 '05 #9
Success! I think...

I got three seperate codes to compile, but only one would
run without run-time errors, ie. bad memory
access/allocation.

Here it is:

#ifndef INCLUDE_ACCESSOR_CAST
#define INCLUDE_ACCESSOR_CAST

template<typename TO, class FROM>
inline TO& accessor_cast(FROM& from)
{
return *(reinterpret_cast<TO*>(&from));
}

template<typename TO, class FROM>
inline const TO& accessor_cast(const FROM& from)
{
return *(reinterpret_cast<const TO*>(&from));
}

#endif
int main()
{
int* blah = new int[125];

int (*krt)[5][5] = accessor_cast<int(*)[5][5]> (blah);

krt[1][3][2] = 45;

delete [] blah;
}

Are we the first people to get a multidimensional array out
of the heap?!
Next step is making a template!
(But I still don't understand why we've turned [5][5][5]
into [5][5] in the casts.)
-JKop
Jul 22 '05 #10
JKop posted:
(But I still don't understand why we've turned [5][5][5]
into [5][5] in the casts.)


I just realized why. For instance one can:

int blah[5];

blah[72] = 6;

The only reason the further 5's are required is to give
shape to the array!
-JKop
Jul 22 '05 #11

"JKop" <NU**@NULL.NULL> wrote in message
news:bW*****************@news.indigo.ie...
Success! I think...

Looks good to me.


Are we the first people to get a multidimensional array out
of the heap?!
I don't think so somehow.


Next step is making a template!

Check out this http://www.boost.org/libs/multi_array/doc/index.html

(But I still don't understand why we've turned [5][5][5]
into [5][5] in the casts.)


It's the same reason that you lose a pair of brackets in this

int a[5];
int* p = a;

When an array decays to a pointer you lose one dimension of the array. So 1d
int array goes to pointer to int, 2d int array goes to pointer to 1d int
array, 3d int array goes to pointer to 2d int array etc. etc.

john
Jul 22 '05 #12
xuatla wrote:
Thanks all of you for the kind help.

I made a mistake. As I mentioned I thought passed-by-pointer is
different with passed-by-value and the change will be kept after
calling the function. Now I know I made a mistake. If "a" is a double
value, not an array, then

testfun( double *a)
{ *a = newvalue; }
and
{
...
double a;
testfun(&a);
}
will change the value of a. But what I used is the pointer to an
array. So it's differnt.


No, the difference is that in one case, you changed what the pointer
points to, in the other case you try to change the pointer itself. If
you'd write:

testfun( double *a)
{
delete a;
a = new double(3.5);
}

You'd get the same problem you got with your array.

Jul 22 '05 #13
xuatla wrote:

I encountered "segmentation fault" and I checked my code, found the
following problem:

I want to reallocate memory for an array.

Others have pointed out the actual error in the code. The bigger
question is, why are you using dynamic arrays at your stage of learning?
You should be using std::vector unless you have a very good reason for
doing something else. Yes, someday you'll need to know how to do that,
but not as a newbie. You are working in C++, not C.


Brian Rodenborn
Jul 22 '05 #14

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

Similar topics

5
by: lixiaoyao | last post by:
hi all I use matrix & vector function to allocate the space myself in c, typedef struct matrix_array newdata; struct matrix_array{ float **sy,*sxx; }; newdata ndata;//new data struct...
12
by: gc | last post by:
I am writing a function that given nx1 vector a and a nx1 b solves a system of equations f(a,c)=b for a nx1 c. While writing the function: 1] Should I allocate the memory for c within the...
8
by: M. Moennigmann | last post by:
Dear all: I would like to write a function that opens a file, reads and stores data into an 2d array, and passes that array back to the caller (=main). The size of the array is not known before...
6
by: Peter Hickman | last post by:
I have a program that requires x strings all of y length. x will be in the range of 100-10000 whereas the strings will all be < 200 each. This does not need to be grown once it has been created....
4
by: marora | last post by:
I have created class definition which contains a charater pointer as one of it's data memeber. The objective is to read some data from a file, and assign it to a data member; Size of data is...
2
by: xhunga | last post by:
I have try a new version of my work. I have put the sizes of the matrix into the matrix. A = number of rows A = number of columns The first element of the matrix is A instead of A. You...
11
by: Divick | last post by:
Hi, can somebody help me figure out how can I make write a function which inturn uses malloc routine to allocate memory which is 2^k aligned? The condition is such that there should not be any...
14
by: raghu | last post by:
Hello , This is Raghu. I have a problem in declaring a structure. Consider struct hai{ int id; char sex; int age; }; here when a variable is instianted for this structure then immediately
17
by: dtschoepe | last post by:
Hi, I have a homework project I am working on, so be forwarned, I'm new to C programming. But anyway, having some trouble with a memory allocation issue related to a char * that is a variable...
9
by: Steven Powers | last post by:
Imagine the following setup class Parent { virtual void doStuff(); } class Child : public Parent { virtual void doStuff(); }
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.