Hello my code is not getting the correct output in copyArgs I am getting a seg f
ID: 3555324 • 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 would compile with out any seg fault.
//In printArgs used %p instead of %s
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.