Web Analytics Made Easy -
StatCounter Strcpy() array question - CodingForum

Announcement

Collapse
No announcement yet.

Strcpy() array question

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Strcpy() array question

    I made this to just seal in strcpy() to my brain, and i noticed that if i leave the brackets empty the compiler says it needs an initializer or needs a specified value to compile. However i can put any value into the brackets and it still compiles. Even with a zero... But if the strcpy() function adds a string terminator to whatever string is declared, why would I still need to put a placeholder in the brackets?

    Code below...



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


    main()
    {

    char yearFirst[0]; <------ HOW DOES THIS still EXECUTE??
    char yearSecond[6];
    char month[5];

    /* when declaring strcpy function, place each copied string before.
    their desired print function.
    or else the print function will print thr same strcpy for each print
    function proceeding it.

    ex.
    strcpy(yearFirst, "Sept., Oct., Nov., Dec., Jan.");
    strcpy(yearSecond, "Mar., Apr., May., Jun. Jul., Aug.");
    followed by:
    printf("These months have 1-31 days: %s\n\n", yearFirst)
    printf("These months have 1-30 days: %s\n\n", yearSecond);

    output will equal both statements saying
    "These months have 1-31: sept oct ...."
    "these months have 1-30: sept oct....."
    */

    strcpy(yearFirst, "Sept., Oct., Nov., Dec., Jan.");
    printf("These months have 1-31 days: %s\n\n", yearFirst);

    strcpy(yearSecond, "Mar., Apr., May., Jun. Jul., Aug.");
    printf("These months have 1-30 days: %s\n\n", yearSecond);

    strcpy(month, "Feb.");
    printf("%s has 1-28 days\n", month);

    return 0;
    }

  • #2
    Passing parameters;

    PHP Code:
    int data 2;
    char somechar "A";

    strcpy(data,"whatever"); 
    will copy the literal "whatever" to the address 2 effectively causing memory corruption from absolute 2 to (2 + length of "whatever");

    The same if the memory is reserved as char (somechar). You can force the strcpy to copy "whatever" to the absolute address "A" (Ascii 65)
    ---------
    PHP Code:
    char yearFirst[0];
    char nextdata;
    char thirddata;

    strcpy(yearFirst,"whatever"
    since you are passing an array,
    the compiler generated code will have the parameter as pointer to the memory location reserved for yearFirst whose length is 0 bytes.

    will copy the literal "whatever" to the absolute location yearFirst is pointing to. And since you reserved only zero memory, these will cause the next variable (nextdata) be overwritten with the "whatever". in this case, the letter "w" and thirddata, with "h"
    Last edited by josephm; Sep 27, 2016, 03:34 AM.

    Comment

    Working...
    X