So I got a book on Security to try and teach myself some morethings about it. Un
ID: 3613798 • Letter: S
Question
So I got a book on Security to try and teach myself some morethings about it. Unfortunately I've run into a bit of code that Idon't really understand what is going on. It reads:int main(int argc, char *argv[]) { char *buff = (char *)malloc(strlen(arv[1])+1); if (buff != NULL) { strcpy(buff, argv[1]); printf("argv[1] = %s. ", buff); } else { /* Couldn't get the memory - recover */ } return 0; }
Now I get certain parts of it but I'm kind of lost on line 2and where buff is defined / what exactly it is. Why it has * inline 2 but not in the other lines. Etc. Any help on what exactly isgoing on would be greatly appreciated.
PS: I realize that in general this program is simply taking ininput from the command line and putting it in memory but thatdoesn't mean I can trace through it.
Thanks!
int main(int argc, char *argv[]) { char *buff = (char *)malloc(strlen(arv[1])+1); if (buff != NULL) { strcpy(buff, argv[1]); printf("argv[1] = %s. ", buff); } else { /* Couldn't get the memory - recover */ } return 0; }
Now I get certain parts of it but I'm kind of lost on line 2and where buff is defined / what exactly it is. Why it has * inline 2 but not in the other lines. Etc. Any help on what exactly isgoing on would be greatly appreciated.
PS: I realize that in general this program is simply taking ininput from the command line and putting it in memory but thatdoesn't mean I can trace through it.
Thanks!
Explanation / Answer
Let me guide you throw this. char is a data type that tells the compiler to set aside spacein memory to hold character(one byte) *is used to define a pointer. it is also a memory location thatholds address of another memory location the function malloc is for memory allocation.... it allocatesthe memory in bytes. after allocation its returns thestarting address of that memory (char *) is used here to change that address into charpointer so that it can be stored in buff. remember buff is thememory location that can hold address. strlen() is a function that returns the length of thearray.soall in all this line tells the compiler to set aside memorylocation the size of the first argument from command line + 1 andsave its starting address in buff. so that buff can be used laterto pint to this memory location.
later in the program the strcpy() function copies the firstargument into the memory pointed to by the buff.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.