Question

If I have allocated some memory, why can't I write character by character in its position? The following printf doesn't output anything. What am I missing here?

int main()
{
        char *newStr = NULL;
        newStr = (char *) malloc ((2) * sizeof(char));
        *newStr = 'a';
        newStr++;
        *newStr = '\0';
        printf("%s", newStr);
}
Was it helpful?

Solution

It's because you're shifting your pointer so printf("%s", newStr); try to print only the \0.

Try this:

    char *newStr = NULL;

    newStr = malloc(2 * sizeof(char));
    *newStr = 'a';
    newStr++;
    *newStr = '\0';
    newStr--;
    printf("%s", newStr);


Or this:

    char *newStr = NULL;
    char *backupedPointer = NULL;

    newStr = malloc(2 * sizeof(char));
    backupedPointer = newStr;
    *newStr = 'a';
    newStr++;
    *newStr = '\0';
    printf("%s", backupedPointer);


And like Matt McNabb says in his comment you should add the free() at the end to release the memory you've allocated (one malloc() = one free(), always) :

    char *newStr = NULL;
    char *backupedPointer = NULL;

    newStr = malloc(2 * sizeof(char));
    backupedPointer = newStr;
    *newStr = 'a';
    newStr++;
    *newStr = '\0';
    printf("%s", backupedPointer);
    free(backupedPointer);


One of the best solutions would be :

    char *newStr = NULL;

    newStr = malloc(2 * sizeof(char));
    newStr[0] = 'a';
    newStr[1] = '\0';
    printf("%s", newStr);
    free(newStr);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top