Correct way of doing this?

This is a discussion on Correct way of doing this? within the C Programming forums, part of the General Programming Boards category; I am getting some strange results from the following code: Code: while (fgets(buffer, 2048, pfile) != NULL) { sscanf(buffer, "%d ...

  1. #1
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    398

    Correct way of doing this?

    I am getting some strange results from the following code:
    Code:
    while (fgets(buffer, 2048, pfile) != NULL)
    {
    	sscanf(buffer, "%d %d", &stid[i], &stsc[i]);
    	printf("%d		%d\n", stid[i], stsc[i]);
    	i++;
    }
    As you can see, its reading from a file with this type of format:

    Code:
    item1 subitem1
    item2 subitem2
    But after the while loop, and I call stsc[0], it contains elements that are supposed to be in stid. But this only happens AFTER the loop. During the loop, the output is correct. I need to use the arrays later on for something else, and with this happening, this isn't possible. Can anyone see if I'm misusing memory in some way?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The code you have posted appear correct. Of course, I don't see the definition of the stid, stsc arrays.

    By the way, not that it will relly change anything, but have you considered using a struct of stid and stsc instead of two arrays?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    398
    Well, here is my declaration
    Code:
    	int* stid		 = (int*)malloc(sizeof(int));
    	int* stsc		 = (int*)malloc(sizeof(int));
    I am not sure whether or not using a struct would be easier or harder. I currently read from a text file with a non-specified amount of lines. With this way, it should work, but doesn't.

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by carrotcake1029 View Post
    Well, here is my declaration
    Code:
    	int* stid		 = (int*)malloc(sizeof(int));
    	int* stsc		 = (int*)malloc(sizeof(int));
    This gives you ... one number each. If you want more, you need to malloc more memory than this.

  5. #5
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    398
    Quote Originally Posted by tabstop View Post
    This gives you ... one number each. If you want more, you need to malloc more memory than this.
    Well, it may be so that it doesn't allocate enough, but it still doesn't solve my problem.
    I am still for some reason getting data that is supposed to be in stid[] inside of stsc[].

    If you want, you can take a look at my whole function right now.
    Code:
    int main(int argc, char* argv[])
    {
    	int* stid	= (int*)malloc(sizeof(int*));
    	int* stsc	= (int*)malloc(sizeof(int*));
    	char* input_file = (char*)malloc(sizeof(char*));
    	char* buffer	 = (char*)malloc(sizeof(char*));
    	FILE* pfile;
    	int i = 0;											
    	float avg = 0.0;
    	int avgtot = 0;										
    	int sort;
    	int j;
    
    	printf("Please enter a file to read "
    		   "(default is scores.txt): \n");				
    
    	scanf("%s", input_file);							
    
    	printf("If you would like sort the data, type the corresponding numerical value:\n");
    	printf("(ID = 0) ");
    	printf("(Grade = 1) ");
    	printf("(None = 2)\n");
    
    	scanf("%d", &sort);
    
    	pfile = fopen(input_file, "r");						
    
    	if (pfile == NULL)									
    	{
    		printf("File could not be read, reverting to default.\n");				
    		pfile = fopen(default_file, "r");				
    	}
    
    	if (pfile == NULL)									
    	{
    		printf("Error finding scores.txt\n");
    		return 1;										
    	}
    
    	printf("\nStudent Letter grades:\n\n");
    	printf("Student ID\t\tGrade\n");
    
    	while (fgets(buffer, 2048, pfile) != NULL)			
    	{
    		sscanf(buffer, "%d%d", &stid[i], &stsc[i]);		
    		printf("%d\t\t%s\n", stid[i], parsegrade(stsc[i]));
    		avgtot += stsc[i];								
    		i++;											
    	}
    
    	avg = (avgtot / i);									
    
    	printf("\nAverage grade: %2.1f	%s\n",	avg, parsegrade(avg));
    
    	for(i = 0; i < 5; i++)
    	{
    		printf("%d\n", stsc[i]);     //This is my test loop that is drawing strange results
    	}
    
    	fclose(pfile);										
    	
    	free(stid);											
    	free(stsc);											
    	free(buffer);										
    	free(input_file);									
    
    
    	return 0;
    }

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by carrotcake1029 View Post
    Well, it may be so that it doesn't allocate enough, but it still doesn't solve my problem.
    Except that it does, of course. You have room for one integer. You put two or five or however many numbers ... somewhere. Where are they going to go? Somewhere else.

    (Since stid and stsc are allocated one after the other, they are probably next to each other in memory; so writing stid[1] actually writes into the space that is really stsc[0], and you write stid[2] into the space that you really stsc[1] -- sort of anyway, since neither stid[1] nor stsc[1] exist, since you only allocate one spot.)

  7. #7
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    398
    Well, I am still getting the same results. Could you show me the correct way to allocate both arrays?

  8. #8
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Easy as pie:
    Code:
    int* stid = malloc(N*sizeof(int));
    and same for stsc, of course. The catch: you have to know N (the number of things) before you start.

  9. #9
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    398
    Quote Originally Posted by tabstop View Post
    Easy as pie:
    The catch: you have to know N (the number of things) before you start.
    Well, I don't, lol. Workarounds?

  10. #10
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by carrotcake1029 View Post
    Well, I don't, lol. Workarounds?
    Guess a number that will be "big enough".

    Use realloc to resize the memory every single time you get a new one.

    If it's a file, read through it once to count how many lines there are, then rewind.

  11. #11
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    398
    Ok, thanks for taking the time to explain it to me. Everything is working well now.

  12. #12
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > char* buffer = (char*)malloc(sizeof(char*));
    And here you're only allocating the size of a pointer for your whole buffer, which to match the fgets() should be 2048. Try this:
    Code:
    printf("sizeof(char *): &#37;u\n", (unsigned) sizeof(char *));
    That will show you how much you're allocating with the above statement. It'll be far less than 2048.

  13. #13
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,167
    Code:
    scanf("%s", input_file);
    http://cpwiki.sf.net/Buffer_overruns
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linux for GNU/Linux is not correct?
    By password636 in forum Linux Programming
    Replies: 8
    Last Post: 03-31-2009, 08:30 PM
  2. Is this correct : passing strings?
    By socket in forum C Programming
    Replies: 15
    Last Post: 11-25-2008, 01:03 PM
  3. correct order to insert new node?
    By campermama in forum C++ Programming
    Replies: 1
    Last Post: 06-16-2004, 07:51 PM
  4. Replies: 1
    Last Post: 05-26-2004, 12:58 AM
  5. Loop until enter correct value
    By jchanwh in forum C Programming
    Replies: 2
    Last Post: 11-27-2001, 12:23 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21