M
mast2as
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;
}
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;
}