hi everyone
I ran into an error when working on this assignment in MS Visual Studio 2008. I need to get a paragraph of text into an array of strings (with each string holding one line) and it must be dynamically allocated.
when the program runs to the strcpy line (indicated by /*PROBLEM HERE*/ below, I get an access violation error from the strcat.asm library. I couldn't find the bug
The "1" is used for testing.
I see this from local variable window of the strcat.asm tab:
+ dst 0x0041573c "1" unsigned char *
+ src 0x0abaf9d4 <Bad Ptr> unsigned char *
here's the code
Code:
#define INPUTFILE "file1.txt"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
int length;
char *stringarray;
int *charactercount;
int *charstring;
int lines = 0;
int c = 0;
int i;
char *tempstring;
char character;
if ((fp = fopen(INPUTFILE, "r")) == NULL)
{
printf ("Error opening file");
getchar();
exit(1);
}
fseek(fp,0,SEEK_END);
length=ftell(fp);
fseek(fp,0,SEEK_SET);
/*count number of lines*/
charstring = malloc(length);
while(fgets(charstring, 63, fp)!=NULL) /*62 is max characters per line*/
{lines++;}
charactercount = calloc(lines, sizeof(int));
fseek(fp,0,SEEK_SET);
for (i = 0; i<lines; i++)
{
while((character = fgetc(fp))!='\n')
{
if(character == EOF){ break;}
c++;
}
charactercount[i]= c;
c=0;
}
for (i=0;i<lines;i++)
{
printf ("%d\n", charactercount[i]);
}
fseek(fp,0,SEEK_SET);
stringarray = malloc(lines * (sizeof (*stringarray)));
if (stringarray!= NULL)
{
for (i=0;i<lines;i++)
{
tempstring = malloc(charactercount[i]*sizeof(char)+1);
fgets(tempstring,63,fp);
charstring=stringarray[i];
stringarray[i] = malloc ((strlen(tempstring)+1));
charstring=stringarray[i];
printf("ZZZ%sZZZ", tempstring);
if (stringarray[i])
{
strcpy(stringarray[i], "1");/*PROBLEM HERE*/
strcpy(stringarray[i], tempstring);/*PROBLEM HERE*/
}
}
}
return 0;
}