I encountered "segmentati on fault" and I checked my code, found the
following problem:
I want to reallocate memory for an array.
I defined the following function:
int reallocateMemor y( 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}
reallocateMemor y( 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
reallocateMemor y, "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 13 2501
"xuatla" <xu****@gmail.c om> wrote in message
news:40******** ******@gmail.co m... I encountered "segmentati on fault" and I checked my code, found the following problem:
I want to reallocate memory for an array. I defined the following function:
int reallocateMemor y( 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}
reallocateMemor y( 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 reallocateMemor y( 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
On Thu, 15 Jul 2004 00:20:39 -0700, xuatla <xu****@gmail.c om> wrote: I encountered "segmentati on fault" and I checked my code, found the following problem:
I want to reallocate memory for an array. I defined the following function:
int reallocateMemor y( 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}
reallocateMemor y( 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 reallocateMemor y, "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* reallocateMemor y( double *array, int newsize )
{
delete[] array;
return new double[newsize];
}
a = reallocateMemor y( a, 10 );
2) Use a reference
void reallocateMemor y( double*& array, int newsize )
{
delete[] array;
array = new double[newsize];
}
reallocateMemor y( a, 10 );
3) Use a pointer (in your case this would be a pointer to a pointer)
void reallocateMemor y( double** array, int newsize )
{
delete[] *array;
*array = new double[newsize];
}
reallocateMemor y( &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
[...] int reallocateMemor y( 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 functiondeclara tion to
int reallocateMemor y( 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...
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.c om> wrote:
I encountered "segmentati on fault" and I checked my code, found the following problem:
I want to reallocate memory for an array. I defined the following function:
int reallocateMemor y( 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}
reallocateMemor y( 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 reallocateMemor y, "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* reallocateMemor y( double *array, int newsize ) { delete[] array; return new double[newsize]; }
a = reallocateMemor y( a, 10 );
2) Use a reference
void reallocateMemor y( double*& array, int newsize ) { delete[] array; array = new double[newsize]; }
reallocateMemor y( a, 10 );
3) Use a pointer (in your case this would be a pointer to a pointer)
void reallocateMemor y( double** array, int newsize ) { delete[] *array; *array = new double[newsize]; }
reallocateMemor y( &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
"xuatla" <xu****@gmail.c om> wrote in message
news:40******** ******@gmail.co m... 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
"xuatla" <xu****@gmail.c om> wrote in message
news:40******** ******@gmail.co m... 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
John Harrison posted: "xuatla" <xu****@gmail.c om> wrote in message news:40******** ******@gmail.co m... 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
multidemensiona l 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_ACCESSO R_CAST
#define INCLUDE_ACCESSO R_CAST
template<typena me TO, class FROM>
inline TO& accessor_cast(F ROM& from)
{
return *(reinterpret_c ast<TO*>(&from) );
}
template<typena me TO, class FROM>
inline const TO& accessor_cast(c onst FROM& from)
{
return *(reinterpret_c ast<const TO*>(&from));
}
#endif
int main()
{
int* blah = new int[125];
int (*krt)[5][5][5] = accessor_cast<i nt([5][5][5][5])>
(blah);
*krt[1][3][2] = 45;
delete [] blah;
}
-JKop
> The following is a mess. What I tried to get was a multidemensiona l 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_ACCESSO R_CAST #define INCLUDE_ACCESSO R_CAST
template<typena me TO, class FROM> inline TO& accessor_cast(F ROM& from) { return *(reinterpret_c ast<TO*>(&from) ); }
template<typena me TO, class FROM> inline const TO& accessor_cast(c onst FROM& from) { return *(reinterpret_c ast<const TO*>(&from)); }
#endif
int main() { int* blah = new int[125];
int (*krt)[5][5][5] = accessor_cast<i nt([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<i nt[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<i nt(*)[5][5]> (blah);
Nothing was compiled so apologies in advance for any stupid mistakes.
john
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_ACCESSO R_CAST
#define INCLUDE_ACCESSO R_CAST
template<typena me TO, class FROM>
inline TO& accessor_cast(F ROM& from)
{
return *(reinterpret_c ast<TO*>(&from) );
}
template<typena me TO, class FROM>
inline const TO& accessor_cast(c onst FROM& from)
{
return *(reinterpret_c ast<const TO*>(&from));
}
#endif
int main()
{
int* blah = new int[125];
int (*krt)[5][5] = accessor_cast<i nt(*)[5][5]> (blah);
krt[1][3][2] = 45;
delete [] blah;
}
Are we the first people to get a multidimensiona l 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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
ndata.sy=matrix(1,nvar,1,nstep);
ndata.sxx=vector(1,nstep);
|
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 function and return
the allocated memory?
something that leads to
double *solve(const double *a,const double *b,int n)
{
double *c;
|
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 opening to the
file.
I fail to write a function that allocates memory for a 2d array and
returns it to main. I was trying to pass a pointer to the array back
to main, but main cannot access the data. The simplified code (no
opening of file, but...
|
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.
Should I allocate x strings of y length or should I allocate a single string x *
y long? Which would be more efficient and / or portable?
Thank you.
|
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 not known in the begining.
We can assume that it will not exceed 256;
class definition:
| |
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 can not use the row 0, and the column 0.
|
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 memory leak and it
should not also waste memory.
Thanks,
Divick
|
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
|
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 inside of a
structure. I keep getting segmentation fault errors and I am having
trouble understanding why. Here's the parts of the code in question...
This is part of the .h file where the struct us defined...
|
by: Steven Powers |
last post by:
Imagine the following setup
class Parent
{
virtual void doStuff();
}
class Child : public Parent
{
virtual void doStuff();
}
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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 then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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 we have to send another system
| |