Thread: String var corrupted after strcpy from another string

  1. #1
    Registered User
    Join Date
    Jun 2012
    Posts
    82

    String var corrupted after strcpy from another string

    So, I'm suppose to copy the ID that user input into another variable. But somehow, it gives me some problem/error.

    For first attempt, no error shown. But, the spacing was off.
    It would be like

    ID :

    S0001

    For second attempt, it shown " stacked variable around 'ID' is corrupted"

    So, what's exactly causing this?

    First attempt,
    Code:
    typedef {
    
    int highest_sale, qtr_total;
    char highest_id[6],id[6];
    
    }quarter;
    
    
    int main()
    {
    
    int j;
    quarter sales[3];
    
    for(j=0;j<3;j++)
    {
           scanf("%s", &sales[j].id);
    }
    
    for(j=0;j<3;j++)
    {
    	if(sales[0].highest_sale < sales[j].qtr_total)
    	{
    		sales[0].highest_sale = sales[j].qtr_total;
    		strcpy(sales[0].highest_id,sales[j].id);
    	}//if
    }//for
    
      printf("ID : %s", ids);
      return 0;
    }
    Second attempt,
    Code:
    typedef {
    
    int highest_sale, qtr_total;
    char highest_id[6],id[6];
    }quarter;
    
    
    int main()
    {
    
    quarter sales[3];
    
    int j;
    char ids[6];
    
    for(j=0;j<3;j++)
    {
    	if(sales[0].highest_sale < sales[j].qtr_total)
    	{
    		sales[0].highest_sale = sales[j].qtr_total;
    		strcpy(ids,sales[j].id);
    	}//if
    }//for
    
      printf("ID : %s", ids);
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    For second attempt, it shown " stacked variable around 'ID' is corrupted"
    Uh...you have no variable named ID, so I'm guessing you're not actually giving us the code, or you've improperly transcribed your error message. If you want help, the code and the error message must match exactly and coincide with each other.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Yes the id[6] is in there, part of the quarter struct typedef.

    Since sales (and thus sales.id[]), is created in main, the contents of sales.id[] is just junk - not a string of char's with an end of string marker. Make it a string of the proper length (in the second example), and see how it does.

  4. #4
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Code:
    typedef {
    int highest_sale, qtr_total;
    char highest_id[6],id[6];
    }quarter;
    Does this actually compile?

    Bye, Andreas

  5. #5
    Registered User
    Join Date
    Jun 2012
    Posts
    82
    Yeah, I was trying to simplify it because it's gonna be lengthy, but oh well...there you go.
    And sometimes, it displays

    "Unhandled exception at 0x530a3330 in PCD2Assignment.exe: 0xC0000005: Access violation."

    But this is not always the case. If replaced salesman_quarter[0].highest_id with another char var like id[6], it will appear the Stacked Around Variable 'id' corrupted error, or it will display
    the id then followed by a bunch of junk values.

    ps: Please ignore the previous codes.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define     displayField            "%s %14s %14s %14s %14s %21s","Salesman ID", "Qtr1", "Qtr2", "Qtr3", "Qtr4", "Total Sales"
    #define  qtrSales_Total            salesman_quarter[i].quarter_sales_total = salesman_quarter[i].quarter_sales[0] + salesman_quarter[i].quarter_sales[1] + salesman_quarter[i].quarter_sales[2] + salesman_quarter[i].quarter_sales[3]
    #define     qtrSales_GrandTotal    salesman_quarter[0].grand_total += salesman_quarter[i].quarter_sales_total
    #define     qtrSales_AvgSales        salesman_quarter[0].avg_sale = salesman_quarter[0].grand_total / SIZE
    #define     getID_Sales            salesman_quarter[i].id, &salesman_quarter[i].quarter_sales[0], &salesman_quarter[i].quarter_sales[1], &salesman_quarter[i].quarter_sales[2], &salesman_quarter[i].quarter_sales[3]
    #define     printID_Sales            salesman_quarter[i].id, salesman_quarter[i].quarter_sales[0], salesman_quarter[i].quarter_sales[1], salesman_quarter[i].quarter_sales[2], salesman_quarter[i].quarter_sales[3],salesman_quarter[i].quarter_sales_total
    
    int QtrReport();
    
    typedef struct
    {
        char id[6];
        char highest_id[6];
        float quarter_sales[4];
        float quarter_sales_total;
        float highest_sale;
        float avg_sale;
        float grand_total;
    }QUARTER;
    
    
    int QtrReport()
    {
        //Local Variables
        int selection;
        int SIZE=2;
            int salesman_num=3;
        char id[6]=" ";
        FILE *salesPtr;
        FILE *memoryPtr;
        
        
        //Open memory for reading previous SIZE
        memoryPtr=fopen("memory.txt","r");
        fscanf(memoryPtr, "%d", &SIZE);
        fclose(memoryPtr);
        //read
    
    
        //Open memory for storing latest SIZE for future uses
        memoryPtr= fopen("memory.txt","w");
        if(salesman_num>0)
        {
            SIZE += salesman_num;
            fprintf(memoryPtr, "%d", SIZE);
        }
        fclose(memoryPtr);
        //write
    
    
        //Open memory for reading SIZE to control the Loop for     printing out information
        memoryPtr=fopen("memory.txt","r");
        fscanf(memoryPtr, "%d", &SIZE);
        fclose(memoryPtr);
        //read
        
        //Open sales for reading in the infos & validate
        salesPtr = fopen("sales.txt", "r");
        if(!salesPtr)
        {
            printf("ERROR");
            system("pause");
            exit(-1);
        }
    
    
        printf(displayField);
        while(!feof(salesPtr))
        {
            for(i=0;i<SIZE;i++)
            {
                fscanf(salesPtr, "%[^|]|RM%f|RM%f|RM%f|RM%f", getID_Sales);
                qtrSales_Total;
                qtrSales_GrandTotal;
                qtrSales_AvgSales;
                printf("\n%s %20.2f %15.2f %15.2f %15.2f%15.2f", printID_Sales);
            }//for
                
        }//while
    
    
        for(j=0;j<SIZE;j++)
        {
            if(salesman_quarter[0].highest_sale < salesman_quarter[j].quarter_sales_total)
            {
                salesman_quarter[0].highest_sale = salesman_quarter[j].quarter_sales_total;
                strcpy(salesman_quarter[0].highest_id,salesman_quarter[j].id);
            }//if
        }//for
    
    
        printf("\n\nAverage sale by all salesmen is RM%.2f",salesman_quarter[0].avg_sale);
        printf("\nHighest sale RM%.2f is achieved by %s\n\n", salesman_quarter[0].highest_sale,salesman_quarter[0].highest_id);
                
        fclose(salesPtr);
        system("pause");
        system("cls");
        return SIZE;
        
        
    }
    
    int main(void)
    {
       int holder;
    
       holder=QtrReport();
       return 0;
    }
    Last edited by xeon321; 11-05-2012 at 06:11 AM.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You have to add "struct" after the typedef, for the second example to compile. I didn't try the first example.

    @xeon321
    Add some lines of code like this, right after you scanf's, (any input), to see how your strings are. strcpy needs good strings - properly terminated, and not overlapping.

    Code:
    printf("StringName: %s  Hit enter to continue\n",stringName); scanf(" %c",&garbageChar;  //pause it & check it

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    xeon, that code will not even compile. It is apparently making use of an array named salesman_quarter, but no such array is ever defined.

    You are trying to unroll loops, and to construct multiple arguments for function calls, using macros. Such techniques make your code extremely difficult for a mere mortal to diagnose.


    I suggest

    1) Eliminate the macro trickery. It makes your code harder to get right and (if you manage to get it right) fragile if you ever need to change it. The particular tricks you are using are a really bad idea.

    2) Try eliminating code in order to create a SMALL but COMPLETE sample of ACTUAL code that exhibits your problems when compiled and run. In the process of creating that sample, you might realise what the problem is - and not need further help. Worst case is that you will end up with a sample of code that doesn't rely on other people to do mental gymnastics - so someone can probably then provide useful help.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Code:
    while(!feof(salesPtr))
    {
        for(i=0;i<SIZE;i++)
        {
            fscanf(salesPtr, "%[^|]|RM%f|RM%f|RM%f|RM%f", getID_Sales);
    FAQ > Why it's bad to use feof() to control a loop - Cprogramming.com

    And always check the return value of fscanf() (and also fopen()).

    Bye, Andreas

  9. #9
    Registered User
    Join Date
    Jun 2012
    Posts
    82
    Hmm, alright then. I will run through the books + the tutorials again and rewrite everything. Thanks for the help , appreciate it

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 11-10-2011, 06:00 PM
  2. Replies: 5
    Last Post: 08-10-2011, 05:25 AM
  3. sprintf corrupted output using string as argument
    By Ravenlore in forum C++ Programming
    Replies: 8
    Last Post: 05-09-2011, 06:03 AM
  4. global string gets corrupted
    By impz in forum C Programming
    Replies: 2
    Last Post: 08-08-2007, 05:28 AM
  5. Create a new string before using strcpy?
    By Boksha in forum C++ Programming
    Replies: 3
    Last Post: 04-26-2002, 09:25 AM