473,387 Members | 1,745 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,387 software developers and data experts.

Newbee array pointer question

Why ist the following code not working?
I want to initialize a string in function, but I am
getting those STATUS_ACCESS_VIOLATION exceptions.
#include <stdio.h>
#include <stdlib.h>

void init(char* buffer)
{
buffer = (char*) malloc(6 * sizeof(char));
buffer[0] = 'H';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'l';
buffer[4] = 'o';
buffer[5] = '\0';
}

int main()
{
char* buffer;
init(buffer);
printf("%s", buffer);
}
Any workaround or how to for this?
TIA,
Martin
Nov 14 '05 #1
10 1527
Martin Andert <ma***********@gmx.de> scribbled the following:
Why ist the following code not working?
I want to initialize a string in function, but I am
getting those STATUS_ACCESS_VIOLATION exceptions.
#include <stdio.h>
#include <stdlib.h> void init(char* buffer)
{
buffer = (char*) malloc(6 * sizeof(char));


This is a very common newbie problem. C parameter passing is strictly
by value, even if the parameter's type is a pointer. Therefore you're
only modifying the init() function's local copy of buffer here. Try
passing a pointer to buffer instead.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"No, Maggie, not Aztec, Olmec! Ol-mec!"
- Lisa Simpson
Nov 14 '05 #2
Martin Andert wrote:

Why ist the following code not working?
I want to initialize a string in function, but I am
getting those STATUS_ACCESS_VIOLATION exceptions.

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

void init(char* buffer)
char *init(void)
{
char *buffer;

so you don't create a memory leak, and can return the pointer.
{
buffer = (char*) malloc(6 * sizeof(char));
buffer = malloc(6);

suffices and is better. By definition sizeof char is 1.
buffer[0] = 'H';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'l';
buffer[4] = 'o';
buffer[5] = '\0';
return buffer; }

int main()
{
char* buffer;
init(buffer);
buffer = init();
printf("%s", buffer);
}

Any workaround or how to for this?


See above.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #3
Martin Andert wrote:

Why ist the following code not working?
I want to initialize a string in function, but I am
getting those STATUS_ACCESS_VIOLATION exceptions.

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

void init(char* buffer)
{
buffer = (char*) malloc(6 * sizeof(char));
buffer[0] = 'H';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'l';
buffer[4] = 'o';
buffer[5] = '\0';
}

int main()
{
char* buffer;
init(buffer);
printf("%s", buffer);
}

Any workaround or how to for this?

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

void init(char **buffer)
{
*buffer = malloc(6 * sizeof **buffer);
if (*buffer != NULL) {
buffer[0][0] = 'H';
buffer[0][1] = 'e';
buffer[0][2] = 'l';
buffer[0][3] = 'l';
buffer[0][4] = 'o';
buffer[0][5] = '\0';
}
}

int main(void)
{
char *buffer;

init(&buffer);
if (buffer != NULL) {
printf("%s\n", buffer);
free(buffer);
}
return 0;
}

--
pete
Nov 14 '05 #4
On Mon, 1 Nov 2004 17:56:41 UTC, ma***********@gmx.de (Martin Andert)
wrote:
Why ist the following code not working?
I want to initialize a string in function, but I am
getting those STATUS_ACCESS_VIOLATION exceptions.

It works perfectly as designed.
#include <stdio.h>
#include <stdlib.h>

void init(char* buffer)
You receives the address of a buffer here.

You should change the interface to this function as you has to deliver
a pointer here.

void *init(void)

{
buffer = (char*) malloc(6 * sizeof(char));
Now you overreides the local copy of the bufferaddress. By that: the
cast is superflous. You tries to hide the possible case that you miss
the prototype of malloc, going into the lands of undefined behavior.
But even here as you have included stdlib.h the cast does nothing.

sizeof char is always and under any circumstance 1. Mulitplies you in
reality each and anyxthing with one? No? Why not? You should do that
as you does in your applications.

malloc() can fail. It indicates this by returning a NULL pointer
constant. It is on you to check that and act on the error.

buffer[0] = 'H';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'l';
buffer[4] = 'o';
buffer[5] = '\0';
You fille the malloced buffer.

But NOW you looses the address of the allocated buffer, producing a
memory leak.
}

int main()
{
char* buffer;
init(buffer);
As you had changed the interface
buffer = init();
printf("%s", buffer);
}
Any workaround or how to for this?


You creates a local pointer and gives its currently undefined content
to a function that does nothing with that but overwrites it with an
address it gets from malloc. As your function returns nothing it can't
change the content of your local pointer - so you works in any way
with an uninitialised pointer, having produced a memory leak as the
address you gots from malloc gets loose during return from init().

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #5
Try This

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

void init(char * buffer)
{
int i = 0;
*buffer = 'H';
*(buffer + (++i))= 'e';
*(buffer + (++i))= 'l';
*(buffer + (++i))= 'l';
*(buffer + (++i))= 'o';
*(buffer + (++i))= '\0';
}

int main()
{
char* buffer;
buffer = (char*) malloc(6 * sizeof(char));
if(buffer == NULL){
printf("cannot allocate memory\n");
exit(1);
}

init(buffer);
printf("string is %s", buffer);
}
Nov 14 '05 #6
Excluded_Middle wrote:
#include <stdlib.h> char* buffer;
buffer = (char*) malloc(6 * sizeof(char));
That cast isn't needed in C, and could have supressed a warning
if you had forgotten to include stdlib.h

This newsgroup's idiomatic way of dynamically allocating
memory for an array of any type is:
#include <stdlib.h>
pointer = malloc(nmemb * sizeof *pointer);

sizeof(char) is always equal to one, so for strings
pointer = malloc(string_length + 1);
and
pointer = malloc(sizeof "string literal");
are also good ways.

exit(1);


That (1) doesn't have a portable meaning in C.

--
pete
Nov 14 '05 #7
ma***********@gmx.de (Martin Andert) wrote in message news:<9a**************************@posting.google. com>...
Why ist the following code not working?
I want to initialize a string in function, but I am
getting those STATUS_ACCESS_VIOLATION exceptions.
#include <stdio.h>
#include <stdlib.h>

void init(char* buffer)
{
buffer = (char*) malloc(6 * sizeof(char));
buffer[0] = 'H';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'l';
buffer[4] = 'o';
buffer[5] = '\0';
}

int main()
{
char* buffer;
init(buffer);
printf("%s", buffer);
}
Any workaround or how to for this?
TIA,
Martin


If you need to write to a parameter, then you need to pass a pointer
to it. In this case, you want to modify a pointer value, so you pass
a pointer to it:

void init(char **buffer)
{
*buffer = malloc(6);
(*buffer)[0] = 'H';
(*buffer)[1] = 'e';
/* yadda yadda yadda */
}

int main (void)
{
char *buffer;
init(&buffer);
printf("%s\n", buffer);
return 0;
}

Although Joona's method (returning the pointer value) is preferable.
In case malloc() fails, it will return NULL. That way, you can test
to make sure the malloc() succeeded before trying to access the
buffer:

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

char *init(void)
{
char *buf = malloc(6);
if (buf)
{
strcpy (buf, "Hello");
}

return buf;
}

int main(void)
{
char *buffer = init();
if (buffer)
printf ("%s\n", buffer);
else
printf ("malloc() failed in init()!\n");

return 0;
}
Nov 14 '05 #8
John Bode <jo*******@my-deja.com> scribbled the following:
Although Joona's method (returning the pointer value) is preferable.
In case malloc() fails, it will return NULL. That way, you can test
to make sure the malloc() succeeded before trying to access the
buffer:


Surely you mean Herbert's method? Mine was indeed passing a pointer to
a pointer.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"A bicycle cannot stand up by itself because it's two-tyred."
- Sky Text
Nov 14 '05 #9
Joona I Palaste wrote:
John Bode <jo*******@my-deja.com> scribbled the following:
Although Joona's method (returning the pointer value) is
preferable. In case malloc() fails, it will return NULL. That
way, you can test to make sure the malloc() succeeded before
trying to access the buffer:


Surely you mean Herbert's method? Mine was indeed passing a
pointer to a pointer.


Poking around, AFAICS I was the only one suggesting returning the
pointer.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #10
CBFalconer <cb********@yahoo.com> wrote in message news:<41***************@yahoo.com>...
Joona I Palaste wrote:
John Bode <jo*******@my-deja.com> scribbled the following:
Although Joona's method (returning the pointer value) is
preferable. In case malloc() fails, it will return NULL. That
way, you can test to make sure the malloc() succeeded before
trying to access the buffer:


Surely you mean Herbert's method? Mine was indeed passing a
pointer to a pointer.


Poking around, AFAICS I was the only one suggesting returning the
pointer.


This is what I get for posting before I'm actually awake.

But it's still the right thing to do, no matter who suggested it.
Nov 14 '05 #11

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

Similar topics

9
by: sangeetha | last post by:
Hello, Is there any performance difference in using of the following two declaration? int (*ptr); //Array of 10 int pointers int *ptr; // pointer-to-array of 10. Regards, Sangeetha.
51
by: Pedro Graca | last post by:
I run into a strange warning (for me) today (I was trying to improve the score of the UVA #10018 Programming Challenge). $ gcc -W -Wall -std=c89 -pedantic -O2 10018-clc.c -o 10018-clc...
4
by: Christian Maier | last post by:
Hi After surfing a while I have still trouble with this array thing. I have the following function and recive a Segmentation fault, how must I code this right?? Thanks Christian Maier
9
by: subramanian100in | last post by:
The following portion is from c-faq.com - comp.lang.c FAQ list · Question 6.13 int a1 = {0, 1, 2}; int a2 = {{3, 4, 5}, {6, 7, 8}}; int *ip; /* pointer to int */ int (*ap); /* pointer to...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
marktang
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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,...
0
jinu1996
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...

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.