Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello my code is not getting the correct output in copyArgs I am getting a seg f

ID: 3555325 • Letter: H

Question

Hello my code is not getting the correct output in copyArgs I am getting a seg fault

the parameters are ./a.out alpha gamma beta

the output ignores the first parameter and it should be alpha gamma beta

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void printArgs(char **args) {
   while (*args)
      printf("%s ", *args++);
}

void burnArgs(char **args, int argc) {
   while (argc--) {
      **args = 'X';
      *args++ = NULL;
   }
}

void copyArgs(char ***dupArgs, char **argv) {
   for(; *++argv;(*dupArgs)++) {
      *dupArgs = malloc(sizeof(char *));
      **dupArgs = malloc(strlen(*argv) +1);
      memcpy(**dupArgs, *argv, strlen(*argv)+1);
   }
   *++dupArgs = malloc(sizeof(char *));
   *dupArgs = NULL;

}


void main(int argc, char **argv) {
   char **dupArgs;
   copyArgs(&dupArgs, argv);
   burnArgs(argv, argc);
   printArgs(dupArgs);
}

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void printArgs(char **args) {
   while (*args)
      printf("%p ", *(args++));
}

void burnArgs(char **args, int argc) {
   while (argc--) {
      **args = 'X';
      *args++ = NULL;
   }
}

void copyArgs(char ***dupArgs, char **argv) {
   for(; *++argv;(*dupArgs)++) {
      *dupArgs = malloc(sizeof(char *));
      **dupArgs = malloc(strlen(*argv) +1);
      memcpy(**dupArgs, *argv, strlen(*argv)+1);
   }
   *(++dupArgs) = malloc(sizeof(char *));
   *dupArgs = NULL;

}


void main(int argc, char **argv)
{
   char **dupArgs;
   copyArgs(&dupArgs, argv);
   burnArgs(argv, argc);
// printArgs(dupArgs);
}

// This code will work , without segfault, what i have changed is , In the printArgs function used %p instead of %s to print :)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote