Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9160203
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T13:40:55+00:00 2026-06-17T13:40:55+00:00

I haven’t used C in a long time and apparently I’ve forgotten more than

  • 0

I haven’t used C in a long time and apparently I’ve forgotten more than I thought. While attempting to use malloc() to allocate a string, I keep getting the old data for that string, including it’s old, longer length when the requested space is shorter. The circumstance do include the pointer to the string being free()’d and set to NULL. Here is a sample run of what I see in my terminal:

yes, quit, or other            (<-message from program)
oooo                           (<-user input; this will be put to upper case and token'd)

------uIT LENGTH:4             (<-debug message showing length of userInputToken)

preC--tmp:                     (<-contents of tmp variable)

pstC--tmp:OOOO                 (<-contents of temp variable)
bad input                      (<-program response)
yes, quit, or other
yes

------uIT LENGTH:3

preC--tmp:OOOO                 (<-: tmp = malloc(sizeof(char)*(strlen(userInputToken)-1)); )

pstC--tmp:YESO                 (<-: strncpy(tmp,userInputToken,strlen(userInputToken)-1);  )
bad input
yes, quit, or other
yes

------uIT LENGTH:3

preC--tmp:YESO

pstC--tmp:YESO
bad input
yes, quit, or other
quit

------uIT LENGTH:4

preC--tmp:YESO

pstC--tmp:QUIT                 (<-: Successful quit because I only did 4 chars; if 5 were used, this would have failed)

As you can see, strlen(userInputToken) gets the correct length and it is used to get the correct number of characters copied – but either free() or malloc() doesn’t seem to care about it. I can’t figure out what’s going on here! Is this a punishment for leaving C for Python?

What’s more, the tmp variable should be cleared regardless of free() because it is limited by its scope. Here is the code where everything goes down:

In main.c:

void run() {
    outputFlagContainer *outputFlags = malloc(sizeof(outputFlagContainer));

    while(true) {
        puts("yes, quit, or other");
        outputFlags = getUserInput(outputFlags);
        if (outputFlags->YES) {
            puts("It was a yes!");
        } else if (outputFlags->QUIT) {
            break;
        } else {
            puts("bad input");
        }
    }

    free(outputFlags);
}

In messsageParserPieces.h:

outputFlagContainer *getUserInput(outputFlagContainer *outputFlags) {
    outputFlags = resetOutputFlags(outputFlags);
    char *userInput = NULL;
    char user_input[MAX_INPUT];
    char *userInputToken = NULL;
    char *tmp = NULL;
    char *finalCharacterCheck = NULL;

    // Tokens to search for:
    char QUIT[] = "QUIT";
    char YES[] = "YES";

    userInput = fgets(user_input, MAX_INPUT-1, stdin);
    int i = 0;
    while(userInput[i]) {
        userInput[i] = toupper(userInput[i]);
        i++;
    }

    userInputToken = strtok(userInput, " ");
    if (userInputToken) {
        finalCharacterCheck = strchr(userInputToken, '\n');
        if (finalCharacterCheck) {
            int MEOW = strlen(userInputToken)-1; // DEBUG LINE
            printf("\n------uIT LENGTH:%d\n", MEOW); // DEBUG LINE

            // The problem appears to happen here and under the circumstances that
            // userInput is (for example) 4 characters and then after getUserInput()
            // is called again, userInput is 3 characters long. 
            tmp = malloc(sizeof(char)*(strlen(userInputToken)-1));
            if (tmp == NULL) {
                exit(1);
            }

            printf("\npreC--tmp:%s\n", tmp); // This shows that the malloc DOES NOT use the given length.

            strncpy(tmp,userInputToken,strlen(userInputToken)-1);

            printf("\npstC--tmp:%s\n", tmp); // Copies in the correct number of characters.

            userInputToken = tmp;
            free(tmp);
            tmp = NULL;
        }
    }

    while (userInputToken != NULL) { // NULL = NO (more) tokens.
        if (0 == strcmp(userInputToken, YES)) {
            outputFlags->YES = true;
        } else if (0 == strcmp(userInputToken, QUIT)) {
            outputFlags->QUIT = true;
        }

        userInputToken = strtok(NULL, " ");
        if (userInputToken) {
            finalCharacterCheck = strchr(userInputToken, '\n');
            if (finalCharacterCheck) {
                tmp = malloc(sizeof(char)*(strlen(userInputToken)-1));
                if (tmp == NULL) {
                    exit(1);
                }
                strncpy(tmp,userInputToken,strlen(userInputToken)-1);
                userInputToken = tmp;
                free(tmp);
                tmp = NULL;
            }
        }
    }
    return outputFlags;
}

I’m assuming this is some kind of obvious error, but I’ve tried googling it for about 2 hours tonight. I can’t think of how to search this that doesn’t bring up a malloc() tutorial – and I have looked at a couple already.

Any insight at all would be greatly appreciated!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T13:40:56+00:00Added an answer on June 17, 2026 at 1:40 pm
    tmp = malloc(sizeof(char)*(strlen(userInputToken)-1));
    if (tmp == NULL) {
        exit(1);
    }
    
    printf("\npreC--tmp:%s\n", tmp); // This shows that the malloc DOES NOT use the given length.
    
    strncpy(tmp,userInputToken,strlen(userInputToken)-1);
    printf("\npstC--tmp:%s\n", tmp); // Copies in the correct number of characters.
    

    This snippet shows that you expect tmp to be initialised with something. This is not true. You must initialise your memory after allocating it. That’s what you do with strncpy.

    There’s also a problem because you are not allocating enough bytes to hold the string, therefore you cannot display it with a plain %s format specifier. You are allocating strlen(userInputToken)-1 bytes and copying that same number. That means there’s no room for a null character, and strncpy will consequently not terminate your string. You should always add one more byte, and if the NULL character will not be copied by strncpy then you must set it yourself:

    size_t length = strlen(userInputToken)-1;
    tmp = malloc(length + 1);
    strncpy(tmp, userInputToken, length);
    tmp[length] = 0;
    

    So, just to be clear, you have three issues:

    1. You display the newly allocated ‘string’ before you initialise it;
    2. You do not allocate enough memory to hold the string
    3. You do not terminate the string (and neither does strncpy because it did not encounter a string terminator within the allowed number of bytes).

    I just spotted something else in your while (userInputToken != NULL) loop… You always to a string compare using userInputToken at the beginning of the loop, but inside the loop (and also in the part above the loop) you do this:

    userInputToken = tmp;
    free(tmp);
    

    That means userInputToken is a dangling pointer. It points to memory that has been freed, and you must NOT use it. You will have to rethink your approach, and allow it to live until it’s no longer needed.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I haven't used ARC yet other than to deal with it when it forces
Haven't used C++ in a while. I've been depending on my Java compiler to
I haven't used the STL much before, but I started to on this huffman
I haven't used multithreading in Clojure at all so am unsure where to start.
I haven't actually dealt with multiple grids on one page in a very long
I haven't been able to figure out how to use strings from resource files
haven't used regex replaces much and am not sure if how I have done
I haven't seen this on the Android docs. Is it safe to use this
I haven't done C++ in a while and can't figure out why following doesn't
I haven't used WPF that much so the solution to this is probably pretty

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.