I want to know if you can Allocate memory without using malloc or calloc, on a char pointer.
as an example:
char *p;
and now i want to do this
*(p 1) = 'd'
printf("%c", *(p 1));
and the output is 'd'. i want this to work without malloc or calloc
CodePudding user response:
You need to assign the pointer with the reference to the object of a suitable type and size.
malloc returns the reference to the suitable block of memory.
You can also assign the statically (or automatically if used in the block context) allocated object.
char data[2];
char *p;
/* ... */
p = data;
*(p 1) = 'd'
printf("%c", *(p 1));
So basically the pointer has to reference the valid object.
CodePudding user response:
C is just human readable assembly, every thing is to be done by the programmer. No fancy garbage collector is a fact but still it has a cutting edge (Rather to say a blunt knife and a file given to you).
Pointer sanitation is a term which you need to be aware of. As soon as you make a pointer variable, you need to assign it some valid memory address. If it is not possible at that time assign it to be NULL.
char * p; // pointing to random location due to grabage value.
*(p 1) = 'd'; // you are overwiting there
printf("%c", *(p 1)); // printing single character
what should be done is.
char *p = NULL;
*(p 1) = 'd'; // this will pop error which you can see in gdb
...
...
