First up, you're not terminating your string with a NUL character (therefore it's not technically a C string). Memory returned from malloc
contains arbitrary bytes, not necessarily zeros.
In other words, that code may cause you trouble since you don't terminate the string correctly - printf
may well collapse in a screaming heap because of that.
On top of that, you're storing the code point 4
, which is CTRL-D in ASCII
. If you want a printable 4
, you need to use '4'
.
And, while we're listing a long litany of problems, there's a vast difference between the variables backedUpPtr
and backedupPtr
(re the capitalisation of the u
), it's good form to free memory that you allocate, and you shouldn't cast the return value of malloc
in C, it can lead to certain subtle errors. In addition, multiplying by sizeof(char)
is unnecessary since it's always one.
Bottom line, I'd start with this code, and go on from there:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
char *newStr = NULL;
char *backedUpPtr = NULL;
newStr = malloc (4); // no need for cast or multiply
if (newStr == NULL) { // and ALWAYS check
printf ("No memory available\n");
return 1;
}
backedUpPtr = newStr;
*newStr = 'a'; // store the a
newStr++;
*newStr = '4'; // store the character 4
newStr++;
*newStr = '\0'; // make into C string
printf ("%s", backedUpPtr);
free (backedUpPtr); // also good form
return 0;
}
although it could be written far simpler with:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
char *newStr = malloc (4);
char *backedUpPtr = newStr;
if (newStr == NULL) {
printf ("No memory available\n");
return 1;
}
*newStr++ = 'a';
*newStr++ = '4';
*newStr = '\0';
printf("%s", backedUpPtr);
free (backedUpPtr);
return 0;
}
or, since four bytes is a rather small amount, there's no real need to use malloc
at all (except for possibly educating yourself about dynamic memory allocation):
#include <stdio.h>
int main (void) {
char backedUpPtr[4], *newStr = backedUpPtr;
*newStr++ = 'a';
*newStr++ = '4';
*newStr = '\0';
printf("%s", backedUpPtr);
return 0;
}
or, even simpler, though not nearly as educational :-)
#include <stdio.h>
int main (void) {
printf ("a4");
return 0;
}