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 740529
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T08:31:35+00:00 2026-05-14T08:31:35+00:00

I need help with debugging this piece of code. I know the problem is

  • 0

I need help with debugging this piece of code. I know the problem is in malloc and free but can’t find exactly where, why and how to fix it. Please don’t answer: “Use gdb” and that’s it. I would use gdb to debug it, but I still don’t know much about it and am still learning it, and would like to have, in the meanwhile, another solution.

Thanks.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>

#define MAX_COMMAND_LENGTH  256
#define MAX_ARGS_NUMBER     128
#define MAX_HISTORY_NUMBER  100

#define PROMPT ">>> "

int num_elems;

typedef enum {false, true} bool;

typedef struct {
    char **arg;     
    char *infile;   
    char *outfile;  
    int background; 
} Command_Info;

int parse_cmd(char *cmd_line, Command_Info *cmd_info)
{
    char *arg;
    char *args[MAX_ARGS_NUMBER];    

    int i = 0;
    arg = strtok(cmd_line, " ");
    while (arg != NULL) {
        args[i] = arg;
        arg = strtok(NULL, " ");
        i++;
    }

    num_elems = i;precisa em free_mem
    if (num_elems == 0)
        return 0;

    cmd_info->arg = (char **) ( malloc(num_elems * sizeof(char *)) );
    cmd_info->infile = NULL;
    cmd_info->outfile = NULL;
    cmd_info->background = 0;

    bool b_infile = false;
    bool b_outfile = false;

    int iarg = 0;
    for (i = 0; i < num_elems; i++)
    {                   
        if ( !strcmp(args[i], "<") )
        {               
            if ( b_infile || i == num_elems-1 || !strcmp(args[i+1], "<") || !strcmp(args[i+1], ">") || !strcmp(args[i+1], "&") )
                return -1;                      

            i++;
            cmd_info->infile = malloc(strlen(args[i]) * sizeof(char));
            strcpy(cmd_info->infile, args[i]);
            b_infile = true;
        }

        else if (!strcmp(args[i], ">"))
        {
            if ( b_outfile || i == num_elems-1 || !strcmp(args[i+1], ">") || !strcmp(args[i+1], "<") || !strcmp(args[i+1], "&") )
                return -1;

            i++;    
            cmd_info->outfile = malloc(strlen(args[i]) * sizeof(char));
            strcpy(cmd_info->outfile, args[i]);
            b_outfile = true;
        }

        else if (!strcmp(args[i], "&"))
        {
            if ( i == 0 || i != num_elems-1 || cmd_info->background )
                return -1;

            cmd_info->background = true;
        }

        else
        {
            cmd_info->arg[iarg] = malloc(strlen(args[i]) * sizeof(char));
            strcpy(cmd_info->arg[iarg], args[i]);
            iarg++;
        }
    }

    cmd_info->arg[iarg] = NULL; 

    return 0;
}


void print_cmd(Command_Info *cmd_info)
{
    int i;  
    for (i = 0; cmd_info->arg[i] != NULL; i++)
        printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]);
    printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]);    
    printf("infile=\"%s\"\n", cmd_info->infile);
    printf("outfile=\"%s\"\n", cmd_info->outfile);
    printf("background=\"%d\"\n", cmd_info->background);
}

void get_cmd(char* str)
{
    fgets(str, MAX_COMMAND_LENGTH, stdin);
    str[strlen(str)-1] = '\0';
}

pid_t exec_simple(Command_Info *cmd_info)
{
    pid_t pid = fork();

    if (pid < 0)
    {
        perror("Fork Error");
        return -1;
    }

    if (pid == 0)
    {
        if ( (execvp(cmd_info->arg[0], cmd_info->arg)) == -1)
        {
            perror(cmd_info->arg[0]);
            exit(1);
        }
    }

    return pid;
}

void type_prompt(void)
{
    printf("%s", PROMPT);
}

void syntax_error(void)
{
    printf("msh syntax error\n");
}

void free_mem(Command_Info *cmd_info)
{
    int i;
    for (i = 0; cmd_info->arg[i] != NULL; i++)
        free(cmd_info->arg[i]);
    free(cmd_info->arg);
    free(cmd_info->infile);
    free(cmd_info->outfile);
}

int main(int argc, char* argv[])
{
    char cmd_line[MAX_COMMAND_LENGTH];
    Command_Info cmd_info;
    //char* history[MAX_HISTORY_NUMBER];

    while (true)
    {   
        type_prompt();

        get_cmd(cmd_line);

        if ( parse_cmd(cmd_line, &cmd_info) == -1)
        {
            syntax_error();
            continue;
        }

        if (!strcmp(cmd_line, ""))
            continue;

        if (!strcmp(cmd_info.arg[0], "exit"))
            exit(0);

        pid_t pid = exec_simple(&cmd_info);

        waitpid(pid, NULL, 0);

        free_mem(&cmd_info);
    }

    return 0;
} 
  • 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-05-14T08:31:35+00:00Added an answer on May 14, 2026 at 8:31 am

    Since strings in C are null-terminated, their actuall size in memory is length+1, so instead of

    cmd_info->infile = malloc(strlen(args[i]) * sizeof(char));

    You should have

    cmd_info->infile = malloc((strlen(args[i])+1) * sizeof(char));

    EDIT: As Aeth said, you need to change every single occurence of malloc to contain space for that additional null character:

    cmd_info->arg = (char **) ( malloc(num_elems * sizeof(char *)) ); //this one can stay, since it determines number of strings, not string length
    cmd_info->outfile = malloc((strlen(args[i])+1) * sizeof(char));
    cmd_info->arg[iarg] = malloc((strlen(args[i])+1) * sizeof(char));
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 357k
  • Answers 357k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The other answers are correct. Here is some code you… May 14, 2026 at 9:40 am
  • Editorial Team
    Editorial Team added an answer you ruin the noConflict concept by reassigning the jquery to… May 14, 2026 at 9:40 am
  • Editorial Team
    Editorial Team added an answer If you get that particular error, you don't actually have… May 14, 2026 at 9:40 am

Related Questions

No related questions found

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.