Hi.
Im trying to malloc memory so that I can create an array of characters, making a word, but when the execution gets to my malloc line, it complains hardcore. (This is C btw, not C++)
Here is the portion of code it gets too, and here is the output dump it gives. Any ideas?:
counter = 0;
nullChecker = 1;
while( nullChecker != 0 )
{
nullChecker = wordArray[codeWord+offset+counter+1];
counter++;
}
printf("counter value: %d\n",counter);
// execution gets here, setting counter to 6 (observed from printf above)
unsigned char *string = malloc(counter + 1);
// using gdb, the program gets here, and suddenly breaks after executing the previous line...
int k;
for(k = 0; k < counter; k++){
unsigned int letterTmp;
letterTmp = wordArray[codeWord+offset+k+1];
printf("string: $s", letterTmp);
string[k] = (char)letterTmp;
}
You're corrupting the heap at some point before that line. Can't tell you where, but the most probable how is that you're writing past the end of a heap-allocated array somewhere.
Im kind of new to malloc, my professor pretty much just told us to use it earlier in the program for a different case, so i took what we did there, and just changed around some values... Im confused however on... why would this be giving me an error at this particular line where all im doing is setting a variable *string to an allocated memory space?
If you write to memory you don't own accidentally, then you could be destroying vital data structures which the heap manager needs.
However, this damage isn't detected until you try to do a malloc() or free() call in many cases.
If you were on Linux I'd say run Valgrind since that's really good at detecting these sorts of errors, but since you're in the Visual C++ forum, I'm guessing you're on Windows. If you show us the entire program then maybe we could help you find the trouble.
Hmm. actually I think i took a different route from the malloc method.. rather than making a string, i just simply printed 1 character at a time, visually doing the same thing my program needs to.
however, it seg faults when i try to print the characters... any idea? I have a feeling its because im using printf("%s") but who knows.
here is the code:
case 248: //newstr
printf("%s%d newstr ", indent, offset);
counter = 0;
nullChecker = 1;
while( nullChecker != 0 ) //checks for when the end of string null character comes.
{
nullChecker = wordArray[codeWord+offset+counter+1];
counter++;
}
Hi.
Im trying to malloc memory so that I can create an array of characters, making a word, but when the execution gets to my malloc line, it complains hardcore. (This is C btw, not C++)
What is a "seg fault"? What is a "glibc"? What is this ".so" file?
I'm asking this, since this is the Visual C++ forum. If you're not using Visual C++, please post in the non-Visual C++ forum.
Bookmarks