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



mast2as@xxxxxxxxx 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
.



Relevant Pages