Pointer initialization question...

N

No Such Luck

Hi all:

Below are two pieces of code that basically perform the same task.
Version A produces a segmentation fault, while version B works
correctly. I understand why version B works correctly, but I do not
understand why version A does not work. It seems to me that in Version
A, a pointer to an array of integers is passed as a parameter to
init_array, and whether that pointer is NULL or not, is should be
initialized as a new array of integers.

Can anyone elaborate? Thanks.

---------Version A (Seg Fault)--------

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

void init_array (int * array, int num)
{
array = (int *)malloc(sizeof(int) * num);
}

int main ()
{
int array_size = 5;
int * array;
init_array(array, array_size);
array[3] = 10; /* This causes a segmentation fault */
return 1;
}

---------Version B (Works Correctly)--------

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

int * init_array (int num)
{
int * array;
array = (int *)malloc(sizeof(int) * num);
return array;
}

int main ()
{
int array_size = 5;
int * array;
array = init_array(array_size);
array[3] = 10;
return 1;
}
 
S

SnaiL

Hey, in version "A" the pointer to the array was not initialized
anyway! Try this:

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

void init_array (int ** array, int num)
{
*array = (int *)malloc(sizeof(int) * num);
}

int main ()
{
int array_size = 5;
int * array;
init_array(&array, array_size);
array[3] = 10; /* This will not causes a segmentation fault */
return 1;
}


// BTW: you must to pass a hard link to the pointer to initialize it,
but not a copy of the pointer. When you passing a copy of the pointer,
the pointer will only be initialized in the scope of the init_array
function.

Sorry for my bad English.
 
D

dandelion

No Such Luck said:
Hi all:

Below are two pieces of code that basically perform the same task.
Version A produces a segmentation fault, while version B works
correctly. I understand why version B works correctly, but I do not
understand why version A does not work. It seems to me that in Version
A, a pointer to an array of integers is passed as a parameter to
init_array, and whether that pointer is NULL or not, is should be
initialized as a new array of integers.

Can anyone elaborate? Thanks.

---------Version A (Seg Fault)--------

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

void init_array (int * array, int num)
{
array = (int *)malloc(sizeof(int) * num);

1. Remove "(int *)". It's not neccesary and may obscure other errors
(missing #include <stdlib.h>).
2. If you want to return a pointer through "array" make it an "int **array"
and assign to *array.
Right now, your newly allocated pointer is lost when your program leaves
the init_array scope.
}

int main ()
{
int array_size = 5;
int * array;
init_array(array, array_size);
array[3] = 10; /* This causes a segmentation fault */

No wonder. int* array is never initialized. See (2) above.
return 1;
}

---------Version B (Works Correctly)--------

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

int * init_array (int num)
{
int * array;
array = (int *)malloc(sizeof(int) * num);
return array;
}

See(1) above. Now arry *is* properly returned and "hey, presto!" your
program works.

<snip>
 
M

Martin Ambuhl

No said:
Hi all:

Below are two pieces of code that basically perform the same task.
Version A produces a segmentation fault, while version B works
correctly. I understand why version B works correctly, but I do not
understand why version A does not work.

This is fully covered in the FAQ, as are the proper return values from
main (yours isn't one of them). Please check the FAQ before posting.
And learn to indent your code.

In the meantime, compare the following to your code:

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

void init_arrayA(int **a, int num)
{
*a = malloc(num * sizeof **a);
}
int *init_arrayB(int num)
{
int *a;
a = malloc(num * sizeof *a);
return a;
}

int main()
{
int array_size = 5;
int *array;
init_arrayA(&array, array_size);
if (!array)
fprintf(stderr, "malloc (A) failed\n");
else {
array[3] = 10;
printf("array[3] (A) = %d\n", array[3]);
free(array);
}
if (!(array = init_arrayB(array_size)))
fprintf(stderr, "malloc (B) failed\n");
else {
array[3] = 12;
printf("array[3] (B) = %d\n", array[3]);
free(array);
}
return 0;
}


array[3] (A) = 10
array[3] (B) = 12

Can anyone elaborate? Thanks.

We really shouldn't. Encouraging people to misbehave by posting
questions without checking the FAQ and following the newsgroup first is
a bad idea.

[OP's code]
#include <stdio.h>
#include <stdlib.h>

void init_array (int * array, int num)
{
array = (int *)malloc(sizeof(int) * num);
}

int main ()
{
int array_size = 5;
int * array;
init_array(array, array_size);
array[3] = 10; /* This causes a segmentation fault */
return 1;
}

---------Version B (Works Correctly)--------

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

int * init_array (int num)
{
int * array;
array = (int *)malloc(sizeof(int) * num);
return array;
}

int main ()
{
int array_size = 5;
int * array;
array = init_array(array_size);
array[3] = 10;
return 1;
}
 
N

No Such Luck

Martin said:
This is fully covered in the FAQ, as are the proper return values from
main (yours isn't one of them). Please check the FAQ before posting.
And learn to indent your code.

Google Groups removes indentations from posts. My code was indented.
In the meantime, compare the following to your code:

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

void init_arrayA(int **a, int num)
{
*a = malloc(num * sizeof **a);
}
int *init_arrayB(int num)
{
int *a;
a = malloc(num * sizeof *a);
return a;
}

int main()
{
int array_size = 5;
int *array;
init_arrayA(&array, array_size);
if (!array)
fprintf(stderr, "malloc (A) failed\n");
else {
array[3] = 10;
printf("array[3] (A) = %d\n", array[3]);
free(array);
}
if (!(array = init_arrayB(array_size)))
fprintf(stderr, "malloc (B) failed\n");
else {
array[3] = 12;
printf("array[3] (B) = %d\n", array[3]);
free(array);
}
return 0;
}


array[3] (A) = 10
array[3] (B) = 12

Can anyone elaborate? Thanks.

We really shouldn't. Encouraging people to misbehave by posting
questions without checking the FAQ and following the newsgroup first is
a bad idea.

"Misbehave?" Oh, please... Thank you for the help, but if you are going
to be a jerk about it, I would rather you not respond. Besides, if my
question had not been in the FAQ, I'm sure you would have labelled it
as an obvious homework question, or something.
If my posts unsettle you, I urge you to utilize your killfile.
 
F

Flash Gordon

Google Groups removes indentations from posts. My code was indented.

Then use a real news client with a real news server. If your ISP does
not provide a news server then the people at http://news.individual.net/
provide one for free. I'm sure I'm not the only one who tends to not
bother reading code with no formatting.

"Misbehave?" Oh, please... Thank you for the help, but if you are
going to be a jerk about it, I would rather you not respond. Besides,
if my question had not been in the FAQ, I'm sure you would have
labelled it as an obvious homework question, or something.

It's in the pointers section of the FAQ, not unreasonable when the
question is about initialising a pointer, and the question starts "I
have a function which accepts, and is supposed to initialize, a
pointer..." which would seem fairly obviously related to your problem.
http://www.eskimo.com/~scs/C-faq/q4.8.html
If my posts unsettle you, I urge you to utilize your killfile.

The problem for you is that if you get the people who can help you to
killfile you then you will find yourself not getting any help.
 
E

E. Robert Tisdale

No said:
Martin said:
Encouraging people to misbehave by posting questions
without checking the FAQ and following the newsgroup first
is a bad idea.

"Misbehave?" Oh, please...
Thank you for the help, but if you are going to be a jerk about it,
I would rather you not respond.
Besides, if my question had not been in the FAQ, I'm sure [that]
you would have labelled it as an obvious homework question, or something.
If my posts unsettle you, I urge you to utilize your killfile.

The comp.lang.c newsgroup has more than its share of indigenous trolls.
You should learn to recognize them and ignore as soon as possible.
 
M

Malcolm

E. Robert Tisdale said:
The comp.lang.c newsgroup has more than its share of indigenous trolls.
You should learn to recognize them and ignore as soon as possible.
You seem to have a troll obsession. In fact we have many irritating posters,
but few trolls, who are people who are deliberately trying to disrupt the
ng.

More importantly, most of us are adults and professional programmers. We
really aren't interested in this subject.
 
B

Barry Schwarz

Hi all:

Below are two pieces of code that basically perform the same task.
Version A produces a segmentation fault, while version B works
correctly. I understand why version B works correctly, but I do not
understand why version A does not work. It seems to me that in Version
A, a pointer to an array of integers is passed as a parameter to
init_array, and whether that pointer is NULL or not, is should be
initialized as a new array of integers.

Can anyone elaborate? Thanks.

---------Version A (Seg Fault)--------

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

void init_array (int * array, int num)
{
array = (int *)malloc(sizeof(int) * num);
}

int main ()
{
int array_size = 5;
int * array;
init_array(array, array_size);

The variable array is passed to init_array by value. (Since it was
not initialized, this invokes undefined behavior which is a different
problem.) When init_array returns, the value of array in main is
still uninitialized.
array[3] = 10; /* This causes a segmentation fault */
return 1;
}

---------Version B (Works Correctly)--------

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

int * init_array (int num)
{
int * array;
array = (int *)malloc(sizeof(int) * num);

The cast is both unnecessary and undesirable.
return array;
}

int main ()
{
int array_size = 5;
int * array;
array = init_array(array_size);
array[3] = 10;
return 1;
}



<<Remove the del for email>>
 
D

dragoncoder

There is no array anywhere. A variable named array which has a type
int* is passed by value to the function. Where a local copy of it is
created and that local variable is malloced to some memory. Thats why
your original array does not gets malloced. What else, the allocated
memory inside the function init_array() is gone and there is no way you
can free it. you have a couple of options to do this thing. The
simplest one you have already showed as the version B. Another one is
as follows.

Pass the address of the pointer (int**) so that it can be modified
inside the function.

void init_array (int ** array, int num)
{
*array = (int *)malloc(sizeof(int) * num);
}

Ofcourse main should be changed for the call of function. Instead it
will be called like this now.
init_array(&array, array_size);

Cheers.
 
X

xarax

dragoncoder said:
There is no array anywhere. A variable named array which has a type
int* is passed by value to the function. Where a local copy of it is
created and that local variable is malloced to some memory. Thats why
your original array does not gets malloced. What else, the allocated
memory inside the function init_array() is gone and there is no way you
can free it. you have a couple of options to do this thing. The
simplest one you have already showed as the version B. Another one is
as follows.

Pass the address of the pointer (int**) so that it can be modified
inside the function.

#include said:
void init_array (int ** array, int num)
{
*array = (int *)malloc(sizeof(int) * num);

*array = malloc(num * sizeof **array);

OR:

*array = calloc(num,sizeof **array);
 
N

No Such Luck

Flash said:
indented.

Then use a real news client with a real news server. If your ISP does
not provide a news server then the people at http://news.individual.net/
provide one for free. I'm sure I'm not the only one who tends to not
bother reading code with no formatting.

I do have a real news server. It's hard to access cross country when
I'm visiting family for the holidays. Thanks for the alternative,
though.
It's in the pointers section of the FAQ, not unreasonable when the
question is about initialising a pointer, and the question starts "I
have a function which accepts, and is supposed to initialize, a
pointer..." which would seem fairly obviously related to your problem.

The problem for you is that if you get the people who can help you to
killfile you then you will find yourself not getting any help.

No, the problem for you is that if half the people here help others
unconditionally, and the other half bitches about "not reading the FAQ"
and "asking obvious homework questions" and eventually killfiles me,
I'll still get a bunch of help.
 
K

Keith Thompson

No Such Luck said:
No, the problem for you is that if half the people here help others
unconditionally, and the other half bitches about "not reading the FAQ"
and "asking obvious homework questions" and eventually killfiles me,
I'll still get a bunch of help.

The problem is that if enough people "help others unconditionally",
this will become known as the place to go to get unconditional help on
any topic, whether it's related to C or not. The quality of such help
will be limited because most of us don't have enough expertise on
whatever the question was about to be able to correct errors, and
actual discussions of the C programming language as defined by the
ANSI/ISO standards will be lost in the noise.

I understand that this actually happened to comp.lang.c++; it took
that newsgroup several years to recover and become useful again.
 
N

No Such Luck

Keith said:
The problem is that if enough people "help others unconditionally",
this will become known as the place to go to get unconditional help on
any topic, whether it's related to C or not.

I agree with you that the specific focus of this group (and other
groups, for that matter) should be strictly enforced, but I think
you're stretching things a bit. I asked a legitimate C programming
language question. It's not like I asked a question regarding math or
sports trivia.

If you feel I have asked a question already answered in the FAQ, or
feel I am trying to have my homework done for me, or are uninterested
in trying to decipher unindented code, or turn to stone at the sight of
incorrect return values for main... Simply, don't respond. And if my
posts continue to annoy you, update your killfile.
 
O

Old Wolf

xarax said:
*array = malloc(num * sizeof **array);
OR:
*array = calloc(num,sizeof **array);

calloc does not generate null pointers. So it is
slower than the malloc version as well as maybe
lulling you into a false sense of security, if it
does generate null pointers on your platform.
So the malloc version is to be preferred.
 
O

Old Wolf

Flash said:
indented.

Then use a real news client with a real news server. If your ISP does
not provide a news server then the people at http://news.individual.net/
provide one for free. I'm sure I'm not the only one who tends to not
bother reading code with no formatting.

news.individial.net doesn't let you post from a web browser.

Many computers have a web browser and not a usenet client,
and many computers do not give administrator access to the
user (eg. at an internet cafe). Google Groups would be good
if it didn't **** up the formatting.
 
O

Old Wolf

Flash said:
indented.

Then use a real news client with a real news server. If your ISP does
not provide a news server then the people at http://news.individual.net/
provide one for free. I'm sure I'm not the only one who tends to not
bother reading code with no formatting.

news.individial.net doesn't let you post from a web browser.

Many computers have a web browser and not a usenet client,
and many computers do not give administrator access to the
user (eg. at an internet cafe). Google Groups would be good
if it didn't **** up the formatting.
 
F

Flash Gordon

news.individial.net doesn't let you post from a web browser.

Many computers have a web browser and not a usenet client,
and many computers do not give administrator access to the
user (eg. at an internet cafe). Google Groups would be good
if it didn't **** up the formatting.

Or lead you in to posting twice? :p

Seriously, I know that in some situations one does not have the option
of a real news client, but a lot of people (not you) use Google because
they don't know there is any other option.

Of course, all the Google users could try complaining about Google
screwing up the formatting. They *might* do something about it.
 
M

Mark McIntyre

No, the problem for you is that if half the people here help others
unconditionally, and the other half bitches about "not reading the FAQ"
and "asking obvious homework questions" and eventually killfiles me,
I'll still get a bunch of help.

Given the people who you're encouraging to killfile you are the people who
know the answers to your question, its more likely you;ll get a bunch of
nonsense answers. Your decision tho.
 
N

No Such Luck

Mark said:
Given the people who you're encouraging to killfile you are the people who
know the answers to your question, its more likely you;ll get a bunch of
nonsense answers. Your decision tho.

Well, look at this thread. Most people have offered help, either after
complaining that I didn't read the FAQ or not. All help offered,
however, has been correct and contains a high degree of correlation
between them.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top