473,467 Members | 1,531 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

allocating mem in a function and assigning a ptr to the first byte of that mem array...

I almost apologize to ask this question but I have been starting at
this code for a bit of time and don't understand what's wrong with it.
I am not arguing about the fact it's good or not coding, it's actually
a shorter version of something more complex that i am doing.

Anway the idea is that there's a func Test which takes a pointer to
void argument, allocate some memory, set this memory with some cotent,
assign the ptr to a void to the first byte of this new alloc memory
and returuns. Normally because our argument points to the first byte
of that memory array * AND THAT THE MEM HASN'T BEEN FREED *, i should
still be able to access the content of that mem array.

But i don't it crashes.

Please help,

cheers -mark

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

//#include <map>
#include <string>

void Test( void *add, char st[2] )
{
char *tt = new char[3];
strcpy( tt, st );
add = (void*)tt;
printf( ">%s\n", (char*)add );
//free( tt );
}

int main( int argc, char **argv )
{
void *a;
Test( a, "ab" );
// crashes here ?
printf( "<< %c\n", *((char*)a + 1 ) );

char *ttt = new char[3];
strcpy( ttt, "ab" );
a = (void*)ttt;
printf( "<< %c\n", *((char*)a + 1 ) );

return 0;
}

Feb 28 '07 #1
8 1737
ma*****@yahoo.com wrote:
I almost apologize to ask this question but I have been starting at
this code for a bit of time and don't understand what's wrong with it.
I am not arguing about the fact it's good or not coding, it's actually
a shorter version of something more complex that i am doing.

Anway the idea is that there's a func Test which takes a pointer to
void argument, allocate some memory, set this memory with some cotent,
assign the ptr to a void to the first byte of this new alloc memory
and returuns. Normally because our argument points to the first byte
of that memory array * AND THAT THE MEM HASN'T BEEN FREED *, i should
still be able to access the content of that mem array.

But i don't it crashes.

Please help,

cheers -mark

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

//#include <map>
#include <string>

void Test( void *add, char st[2] )
{
char *tt = new char[3];
You are posting C++ to comp.lang.c. Don't do that!

If we pretend this is C, your problem is the perennial bug of assigning
a value to a local variable (add) and attempting to access it outside
the function.

If you want to allocate memory in a function, pass a pointer to the
pointer you want to use

void test( void **add char st[2] )
{
*add = malloc(3);

--
Ian Collins.
Feb 28 '07 #2
You are posting C++ to comp.lang.c. Don't do that!

If we pretend this is C, your problem is the perennial bug of assigning
a value to a local variable (add) and attempting to access it outside
the function.

If you want to allocate memory in a function, pass a pointer to the
pointer you want to use

void test( void **add char st[2] )
{
*add = malloc(3);

--
Ian Collins.
Thanks Ian. Yes I mixed C++ and C and was aware it was a perennial
bug, the thing is that i need to go back to some old C code and i am
just not used to it anymore... really sorry, thanks again for putting
me back on the right track - i just started at some code today for so
long, i got lost...

Feb 28 '07 #3
ma*****@yahoo.com wrote:
I almost apologize to ask this question but I have been starting at
this code for a bit of time and don't understand what's wrong with it.
I am not arguing about the fact it's good or not coding, it's actually
a shorter version of something more complex that i am doing.

Anway the idea is that there's a func Test which takes a pointer to
void argument, allocate some memory, set this memory with some cotent,
assign the ptr to a void to the first byte of this new alloc memory
and returuns. Normally because our argument points to the first byte
of that memory array * AND THAT THE MEM HASN'T BEEN FREED *, i should
still be able to access the content of that mem array.

But i don't it crashes.

Please help,

cheers -mark

#include <stdlib.h>
#include <stdio.h>
#include <cmath>
//#include <map>
#include <string>
Not standard C headers. Probably C++.
>
void Test( void *add, char st[2] )
{
char *tt = new char[3];
new operator does not exist in C.
You need to check the value of tt to make sure it's not NULL.
(In your case you should probably catch the exception which is OT
here).
strcpy( tt, st );
add = (void*)tt;
add has the value passed to the function. Here you change the
value that add holds but not the value that was passed to the
function.
printf( ">%s\n", (char*)add );
//free( tt );
If you'll free tt here, add will point to memory that doesn't
belong to it. Also, be consistent, use new with delete and malloc
with free. Given the fact that this is c.l.c you can only use
malloc with free.
}

int main( int argc, char **argv )
{
void *a;
Test( a, "ab" );
a is an uninitialized pointer. You should not use it like that
because it's value is passed to Test but you are not allowed to
use its value. Remember the observations for add from above? That
function didn't change the value it received because it can't, so
add has the same value as before passing it to Test.
// crashes here ?
Probably. You should pass a pointer to your pointer and change
that value:
void Test( void **add, char st[2] )
and use *a=tt;
Pass *a as Test(&a,"ab") and you should set a to NULL before
calling Test.
printf( "<< %c\n", *((char*)a + 1 ) );

char *ttt = new char[3];
strcpy( ttt, "ab" );
a = (void*)ttt;
printf( "<< %c\n", *((char*)a + 1 ) );

return 0;
}
You'll have to decide what language you want to use. You mix C
and C++ too much. Although the C functions exist in C++ you
should probably use what C++ provides if you want to stay with
C++ (and start posting to the appropriate group, probably
c.l.c++), or use only C code and get help here.

--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
Feb 28 '07 #4
Nelu wrote:
ma*****@yahoo.com wrote:
<snip>
> void *a;
Test( a, "ab" );

a is an uninitialized pointer. You should not use it like that
because it's value is passed to Test but you are not allowed to
use its value. Remember the observations for add from above? That
function didn't change the value it received because it can't, so
add has the same value as before passing it to Test.
> // crashes here ?

Probably. You should pass a pointer to your pointer and change
that value:
void Test( void **add, char st[2] )
and use *a=tt;
Pass *a as Test(&a,"ab")
and you should set a to NULL before calling Test.
Sorry, I forgot to mention: it's good to initialize pointers to
NULL just in case, but this initialization is not required in
this case (as opposed to the original one) because you are
passing &a to Test as opposed to a, and &a is valid as the
address of a.

--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
Feb 28 '07 #5
ma*****@yahoo.com wrote:
>
I almost apologize to ask this question but I have been starting at
this code for a bit of time and don't understand what's wrong with it.
I am not arguing about the fact it's good or not coding, it's actually
a shorter version of something more complex that i am doing.

Anway the idea is that there's a func Test which takes a pointer to
void argument, allocate some memory, set this memory with some cotent,
assign the ptr to a void to the first byte of this new alloc memory
and returuns. Normally because our argument points to the first byte
of that memory array * AND THAT THE MEM HASN'T BEEN FREED *, i should
still be able to access the content of that mem array.

But i don't it crashes.

Please help,

cheers -mark

#include <stdlib.h>
#include <stdio.h>
#include <cmath>
no such header file.
>
//#include <map>
#include <string>
no such header file.

If your compiler didn't object to the above, you are using a C++
compiler, which is not a good thing to do to C code.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Feb 28 '07 #6
ma*****@yahoo.com wrote:
>
I almost apologize to ask this question but I have been starting at
this code for a bit of time and don't understand what's wrong with it.
I am not arguing about the fact it's good or not coding, it's actually
a shorter version of something more complex that i am doing.

Anway the idea is that there's a func Test which takes a pointer to
void argument, allocate some memory, set this memory with some cotent,
assign the ptr to a void to the first byte of this new alloc memory
and returuns. Normally because our argument points to the first byte
of that memory array * AND THAT THE MEM HASN'T BEEN FREED *, i should
still be able to access the content of that mem array.

But i don't it crashes.

Please help,

cheers -mark

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

//#include <map>
#include <string>

void Test( void *add, char st[2] )
{
char *tt = new char[3];
strcpy( tt, st );
add = (void*)tt;
printf( ">%s\n", (char*)add );
//free( tt );
}

int main( int argc, char **argv )
{
void *a;
Test( a, "ab" );
// crashes here ?
printf( "<< %c\n", *((char*)a + 1 ) );

char *ttt = new char[3];
strcpy( ttt, "ab" );
a = (void*)ttt;
printf( "<< %c\n", *((char*)a + 1 ) );

return 0;
}
/* BEGIN new.c */

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

void *Test(char *st)
{
char *tt = malloc(strlen(st) + 1);

if (tt != NULL) {
strcpy(tt, st );
printf( ">%s\n", tt);
}
return tt;
}

int main(void)
{
void *a;
char *ttt;

a = Test("ab");
if (a != NULL) {
printf( "<< %c\n", *((char*)a + 1 ) );
}
ttt = malloc(sizeof "ab");
if (ttt != NULL) {
strcpy(ttt, "ab");
a = ttt;
printf( "<< %c\n", *((char*)a + 1 ) );
}
return 0;
}

/* END new.c */

--
pete
Feb 28 '07 #7
ma*****@yahoo.com wrote:
I almost apologize to ask this question but I have been starting at
this code for a bit of time and don't understand what's wrong with it.
I am not arguing about the fact it's good or not coding, it's actually
a shorter version of something more complex that i am doing.

Anway the idea is that there's a func Test which takes a pointer to
void argument, allocate some memory, set this memory with some cotent,
assign the ptr to a void to the first byte of this new alloc memory
and returuns. Normally because our argument points to the first byte
of that memory array * AND THAT THE MEM HASN'T BEEN FREED *, i should
still be able to access the content of that mem array.
After cleaning up your C++-isms, you will still have a logical error in
the way you call your Test() function. Please examine the following
carefully, comparing it to your original.
#include <stdlib.h>
#include <stdio.h>

#if 0
/* mha: apart from the problems of using '//' style comments in usenet
postings, no matter what the language, and with using them with C89
or C90 compilers, where they are errors, commenting out code is best
done with the #if / #endif form exemplified here. */
#include <map>
#endif

#if 0
/* mha: there are no headers named <cmathor <stringin C. */
#include <cmath>
#include <string>
#endif
#include <string.h /* mha */

void Test(void **add /* mha: NB */ , char st[2])
{
#if 0
/* mha: the following is a syntax error in C. A replacement follows.
It appears that your function provides no way to report failures. */
char *tt = new char[3];
#endif
char *tt;
if (!(tt = malloc(3))) {
fprintf(stderr, "%s",
"malloc failed, and 'Test()' provides no way to "
"handle that.\nI'm giving up.\n");
exit(EXIT_FAILURE);
}
strcpy(tt, st);
*add = tt; /* mha: NB */
printf(">%s\n", (char *) *add);

/* mha: it is a good thing you don't free tt; In your off-topic
C++-ism you allocate it with new. Such things are freed with
delete or delete[], not with free(). */
// free( tt );

}

int main(void)
{
void *a;
Test(&a, "ab"); /* mha: NB */
printf("<< %c\n", *((char *) a + 1));
{
#if 0
/* mha: declaration following executable statements in the block
is an error in C89 or C90. I have added a block. */
/* mha: the following is a syntax error in C. A replacement
follows. */
char *ttt = new char[3];
#endif
char *ttt;
if (!(ttt = malloc(3))) {
fprintf(stderr, "%s",
"malloc failed in main(),\nI'm giving up.\n");
free(a);
exit(EXIT_FAILURE);
}
strcpy(ttt, "ab");
a = (void *) ttt;
printf("<< %c\n", *((char *) a + 1));
/* mha: Please clean up after yourself. */
free(ttt); /* mha */
}
/* mha: Please clean up after yourself. */
free(a); /* mha */
return 0;
}
Feb 28 '07 #8
On Wed, 28 Feb 2007 15:47:04 -0500, Martin Ambuhl
<ma*****@earthlink.netwrote:
>ma*****@yahoo.com wrote:
>I almost apologize to ask this question but I have been starting at
this code for a bit of time and don't understand what's wrong with it.
I am not arguing about the fact it's good or not coding, it's actually
a shorter version of something more complex that i am doing.

Anway the idea is that there's a func Test which takes a pointer to
void argument, allocate some memory, set this memory with some cotent,
assign the ptr to a void to the first byte of this new alloc memory
and returuns. Normally because our argument points to the first byte
of that memory array * AND THAT THE MEM HASN'T BEEN FREED *, i should
still be able to access the content of that mem array.

After cleaning up your C++-isms, you will still have a logical error in
the way you call your Test() function. Please examine the following
carefully, comparing it to your original.
#include <stdlib.h>
#include <stdio.h>

#if 0
/* mha: apart from the problems of using '//' style comments in usenet
postings, no matter what the language, and with using them with C89
or C90 compilers, where they are errors, commenting out code is best
done with the #if / #endif form exemplified here. */
#include <map>
#endif

#if 0
/* mha: there are no headers named <cmathor <stringin C. */
#include <cmath>
#include <string>
#endif
#include <string.h /* mha */

void Test(void **add /* mha: NB */ , char st[2])
{
#if 0
/* mha: the following is a syntax error in C. A replacement follows.
It appears that your function provides no way to report failures. */
char *tt = new char[3];
#endif
char *tt;
if (!(tt = malloc(3))) {
fprintf(stderr, "%s",
"malloc failed, and 'Test()' provides no way to "
"handle that.\nI'm giving up.\n");
exit(EXIT_FAILURE);
}
strcpy(tt, st);
*add = tt; /* mha: NB */
printf(">%s\n", (char *) *add);

/* mha: it is a good thing you don't free tt; In your off-topic
C++-ism you allocate it with new. Such things are freed with
delete or delete[], not with free(). */
// free( tt );

}

int main(void)
{
void *a;
Test(&a, "ab"); /* mha: NB */
printf("<< %c\n", *((char *) a + 1));
{
#if 0
/* mha: declaration following executable statements in the block
is an error in C89 or C90. I have added a block. */
/* mha: the following is a syntax error in C. A replacement
follows. */
char *ttt = new char[3];
#endif
char *ttt;
if (!(ttt = malloc(3))) {
fprintf(stderr, "%s",
"malloc failed in main(),\nI'm giving up.\n");
free(a);
exit(EXIT_FAILURE);
}
strcpy(ttt, "ab");
a = (void *) ttt;
printf("<< %c\n", *((char *) a + 1));
/* mha: Please clean up after yourself. */
free(ttt); /* mha */
Same effect as:

free(a);
}
/* mha: Please clean up after yourself. */
free(a); /* mha */
Ouch. This free()'s a pointer that has already been free()'d. Not sure
if this is what you intended.

--
jay
Mar 1 '07 #9

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

Similar topics

21
by: Philipp | last post by:
Hello, a very simple question: Ok I have a class MyClass with a constructor MyClass(int) (no constructor without argument defined) how can I make an array of pointers to objects of that class,...
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...
14
by: Eric Bantock | last post by:
Very basic question I'm afraid. Once an array has been declared, is there a less tedious way of assigning values to its members than the following: myarray=8; myarray=3; myarray=4; myarray=0;...
4
by: TRW1313 | last post by:
I'm looking to populate a byte array of some fixed size to send out over a UDP connection. The data in the byte array is mixed between characters and binary. I'm a beginner to this language. ...
10
by: David Fort | last post by:
Hi, I'm upgrading a VB6 app to VB.net and I'm having a problem with a call to a function provided in a DLL. The function takes the address of a structure which it will fill in with values. I...
94
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring...
28
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
6
by: Francois Grieu | last post by:
Hello, I'm asking myself all kind of questions on allocating an array of struct with proper alignment. Is the following code oorrect ? I'm most interested by the statement t =...
3
by: Chris Saunders | last post by:
My C skills are rather meager so forgive me if I do not express my question clearly enough. Here is a struct that is declared in Windows: typedef struct _REPARSE_GUID_DATA_BUFFER { DWORD...
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
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
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...
0
agi2029
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,...
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: 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.