Click to See Complete Forum and Search --> : Putting values in dynamic array of strings


Heavy Metal
October 8th, 2002, 10:37 AM
I have declared a dynamic array of strings as thus:

char **testfile;

testfile = malloc(sizeof(char *) * 50);

for(j=0;j<count;j++)
{
testfile[j] = malloc(count * sizeof(char));
}

I am reading strings from a file into the array like this:

j=0;
while(fgets(testfile[j], 80, fp) != NULL)
{
j++;
}

But when I deallocate the dynamic memory like this:

for(j=0;j<count;j++)
{
free(testfile[j]);
counter++;
}
free(testfile);

I get an error message:

Debug Error!

Damage: after Normal Block(#42) at 0x00300180

The thing which is confusing me, if i don't fill the array with values, basically commenting out the lines of code which fill the array, I don't get the error message when I deallocate the memory.

I would truly appreciate any words of wisdom regarding my problem.

Thank you,
TJ

Graham
October 8th, 2002, 11:05 AM
char **testfile;

testfile = malloc(sizeof(char *) * 50);
Why 50?
for(j=0;j<count;j++)
Where did "count" come from? What's its value? Is it > 50?
{
testfile[j] = malloc(count * sizeof(char));
is there a reason for using "count" again?
}

I am reading strings from a file into the array like this:

j=0;
while(fgets(testfile[j], 80, fp) != NULL)
is 80 > count - 1?
{
j++;
}

But when I deallocate the dynamic memory like this:

for(j=0;j<count;j++)
{
free(testfile[j]);
counter++;
}
free(testfile);



Almost certainly you are exceeding the bounds of the memory you have allocated, and are trampling all over memory that you shouldn't.

Is this C++ or C? If it's C++, I highly recommend vector<string> and iostreams. If it's C, you have my sympathy.

Heavy Metal
October 8th, 2002, 11:23 AM
You gave me just enough stuff to think about which allowed me to solve the problem. I was overwriting the memory. ometimes when you look at a problem for a while, you look at it with tunnel vision. It helps getting other peoples perspective.

I am working in C. I might be a sadist, but I prefer it to C++. But then I have a lot more experience in C.

Thanks,
TJ

stober
October 8th, 2002, 12:32 PM
Originally posted by Heavy Metal
I am working in C. I might be a sadist, but I prefer it to C++. But then I have a lot more experience in C.
TJ

I used to feel that way too until I decided to get my feet wet and start using it. After several years, I still prefer some of the C-style syntax over C++. I isn't necessary to convert overnight and use strictly C++, do it gradually over some period of time. There are some things in C++ that I will never KNOWINGLY use -- such as templates. If they are simple enough I'll use them as long as I don't have to read them! They are pretty ugly critters to try to read. Other than those ugly templates you will quickly find that there are many advantages that C++ has over C.