473,218 Members | 1,443 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,218 software developers and data experts.

strings, arrays, pointers and dynamic memory allocation

Hi All,

I realize this is not a Palm OS development forum, however, even though
my question is about a Palm C program I'm writing, I believe the topics
are relevant here. This is because I believe the problem centers
around my handling of strings, arrays, pointers and dynamic memory
allocation. Here is the problem I'm trying to solve:

I want to fill a list box with a list of Project Names from a database
(in Palm this is more similar to a file). The Palm OS function I must
call in order to get the Project Names to show up in the list box is
described below:

************************************************** ****************
LstSetListChoices Function
Purpose
Set the items of a list to the array of text string pointers passed to
this function. This functions erases the old list items.

Declared In
List.h

Prototype
void LstSetListChoices (
ListType *listP,
char **itemsText,
Int16 numItems
)
Parameters
- listP
Pointer to a list object.
- itemsText
Pointer to an array of text strings.
- numItems
Number of choices in the list.
Returns nothing.
************************************************** ****************

So, what I want to do is create the array of strings from the database.
Obviously, I don't know how many Project Names I will get from the
database or what size they'll be - so everything needs to be handled
dynamically.

So I define a global variable in the file like this:

static char **itemList;

I also have a structure defined that represents the record of a project
from the database as shown here:

typedef struct {
const char *projectName;
const char *projectDesc;
} ProjectDBRecord;

I also have a "packed" version of that structure defined that is how
the actual record of a project is stored in the database as shown here:

typedef struct {
char rec[1];
} PackedProjectDBRecord;

And I have a function that gets called when the project list needs to
be filled as shown here:

static void FillProjectList(ListType *lst)
{
UInt16 index;
MemHandle h=0;
UInt16 numRecs = DmNumRecordsInCategory(db, dmAllCategories);
char defaultVal[] = "New...";
itemList = (char **) MemPtrNew((sizeof(char *) * numRecs) + 1);
itemList[0] = (char *) MemPtrNew(sizeof(defaultVal));
StrCopy(itemList[0], defaultVal);

for(index = 0; index < numRecs; index++)
{
// get the handle to the record and set busy bit
h = DmQueryRecord(db, index);
if (h) { // could fail due to insufficient memory!
PackedProjectDBRecord *project = MemHandleLock(h);
ProjectDBRecord rec;
UnpackProject(&rec, project);
printf("Here is the project name: %s", rec.projectName);
itemList[index + 1] = (char *)
MemPtrNew(StrLen(rec.projectName));
StrCopy(itemList[index + 1], rec.projectName);
MemPtrUnlock(project);
}
}

LstSetListChoices(lst, itemList, numRecs + 1);
LstDrawList(lst);
}

As you can see, the 'itemList' is initialized in this method.

When this function runs in POSE (Palm OS Emulator), it is telling me
that my program is writing to "a memory location (0x0003D062), which is
in the MemoryManager data structures.....Such an access usually means
that an application allocated a buffer (possibly with MemPtrNew) that
wasn't large enough for its purpose. When the application then tries to
write data to the buffer, it writes off the end of the buffer,
accessing the start of the buffer following it in memory." I see this
error displayed once for each of the following lines of code execute
when they execute:

itemList[0] = (char *) MemPtrNew(sizeof(defaultVal));
StrCopy(itemList[0], defaultVal);

Then finally the program dies with the following error message:

"During a regular checkup, Palm OS Emulator determined that the dynamic
heap chunk with the header address 0x0003D062 got corrupted. The size
of the chunk (%chunk_size) was larger than the currently accepted
maximum (%chunk_max)."

I'm sure I must be doing something obviously wrong here. Can anyone
give me a clue or point me in the right direction? If needed, I can
post the whole program. I just didn't want to "muddy up" the issue
with all the other event handing code. However, it might be helpful to
see the methods that pack and unpack a project, so I have posted them
here:

static void PackProject(ProjectDBRecord *project, MemHandle
projectDBHandle)
{
UInt16 length = 0;
char *s;
UInt16 offset = 0;

length = StrLen(project->projectName) +
StrLen(project->projectDesc) + 2;// 2 for string terminators
// resize the MemHandle and check for errors (0 means no error)
if(MemHandleResize(projectDBHandle, length) == 0)
{
// copy the fields
s = MemHandleLock(projectDBHandle);
DmWrite(s, offset, (char *) project->projectName,
StrLen(project->projectName) + 1);
offset += StrLen(project->projectName) + 1;
DmWrite(s, offset, (char *) project->projectDesc,
StrLen(project->projectDesc) + 1);
MemHandleUnlock(projectDBHandle);
}
}

static void UnpackProject(ProjectDBRecord *project, const
PackedProjectDBRecord *packedProject)
{
const char *s = packedProject->rec;
project->projectName = s;
s += StrLen(s) + 1;
project->projectDesc = s;
s += StrLen(s) + 1;
}
Thanks,
Steve Warsa

Nov 14 '05 #1
5 3716
sw****@msn.com wrote:
I realize this is not a Palm OS development forum, however, even though
my question is about a Palm C program I'm writing, I believe the topics
are relevant here. This is because I believe the problem centers
around my handling of strings, arrays, pointers and dynamic memory
allocation.
There is at least one likely problem - but if this is really a problem
I can't tell because all the functions you use are non-standard functions,
so all people here can do is making guesses what they do and what kind of
arguments they expect, going by what some standard functions do that look
similar. But to get a reasonable answer you have to ask in a group that
deals with the specifics of the Palm OS - it's really off-topic here.
static void FillProjectList(ListType *lst)
{
UInt16 index;
MemHandle h=0;
UInt16 numRecs = DmNumRecordsInCategory(db, dmAllCategories);
char defaultVal[] = "New...";
itemList = (char **) MemPtrNew((sizeof(char *) * numRecs) + 1);
itemList[0] = (char *) MemPtrNew(sizeof(defaultVal));
StrCopy(itemList[0], defaultVal); for(index = 0; index < numRecs; index++)
{
// get the handle to the record and set busy bit
h = DmQueryRecord(db, index);
if (h) { // could fail due to insufficient memory!
PackedProjectDBRecord *project = MemHandleLock(h);
ProjectDBRecord rec;
UnpackProject(&rec, project);
printf("Here is the project name: %s", rec.projectName);
itemList[index + 1] = (char *)
MemPtrNew(StrLen(rec.projectName));
If this MemPtrNew function works similar to malloc() and StrLen() is
like strlen() then you need to allocate one more char - strings in C
have a '\0' character at the end and that's not counted by strlen()
(please note that this is different from sizeof() when applied to a
string literal, as you did above with the string "New...").
StrCopy(itemList[index + 1], rec.projectName);


If it is the case that MemPtrNew() behaves like malloc(), StrLen()
like strlen() and StrCpy() like strcpy() then it would explain why you
get problems with memory corruption since you are always writing one
char past the end of the memory you allocated. Another thing that could
go wrong under these conditions is that MemPtrNew() returns a value that
tells you that you run out of memory, you must check for the possibility.

On the other hand, all this is pure guesswork and it would be much better
to ask in a group concerned with the idiosyncracies of Palm OS.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #2
Hi Jens,

Thanks for the reply. I have posted the documentation for the 3
functions you mention below. The reason I asked in this forum is that
it is much more active and the question seems to center more on "core"
c rather than the specific use of the Palm OS API. The functions used
are (from what I understand) roughly equivalent to the standard C
functions of the same name. Anyway, I think you are probably correct
regarding not adding enough space for the null terminator on the
string.

Thanks again,
Steve Warsa
************************************************** ******************************************
StrLen Function ^TOP^
Purpose
Compute the length of a string.

Declared In
StringMgr.h
Prototype
UInt16 StrLen (
const Char *src
)

Parameters
→ src
Pointer to a string.
Returns
Returns the length of the string in bytes.

Comments
Use this function instead of the standard strlen routine.

This function returns the length of the string in bytes. On systems
that support multi-byte characters, the number returned does not always
equal the number of characters.

StrCopy Function ^TOP^
Purpose
Copy one string to another.

Declared In
StringMgr.h
Prototype
Char *StrCopy (
Char *dst,
const Char *src
)

Parameters
→ dst
Pointer to the destination string.
→ src
Pointer to the source string.
Returns
Returns a pointer to the destination string.

Comments
Use this function instead of the standard strcpy routine.

This function does not work properly with overlapping strings.
MemPtrNew Function ^TOP^
Purpose
Allocate a new memory chunk from the dynamic heap.

Declared In
MemoryMgr.h
Prototype
MemPtr MemPtrNew (
uint32_t size
)

Parameters
→ size
The desired size of the chunk.
Returns
Returns a pointer to a newly allocated chunk if successful, or NULL if
the Memory Manager was unable to allocate a memory chunk of the
requested size.

Comments
This function allocates a non-movable chunk in the dynamic heap and
returns a pointer to that chunk. Applications can use this call to
allocate dynamic memory. User processes should use this call as a
primary dynamic memory allocator.
************************************************** *****************************************

Nov 14 '05 #3
Sorry, but I have made changes to the FillProjectList function and I
still receive the error. Here is the modified source for it below:

static void FillProjectList(ListType *lst)
{
UInt16 index;
MemHandle h=0;
UInt16 numRecs = DmNumRecordsInCategory(db, dmAllCategories);
char defaultVal[] = "New...";
itemList = (char **) MemPtrNew((sizeof(char *) * numRecs) + 1);
itemList[0] = (char *) MemPtrNew(StrLen(defaultVal) + 1);
StrCopy(itemList[0], defaultVal);

for(index = 0; index < numRecs; index++)
{
// get the handle to the record and set busy bit
h = DmQueryRecord(db, index);
if (h) { // could fail due to insufficient memory!
PackedProjectDBRecord *project = MemHandleLock(h);
ProjectDBRecord rec;
UnpackProject(&rec, project);

// do something with the record's contents here
itemList[index + 1] = (char *)
MemPtrNew(StrLen(rec.projectName) + 1);
StrCopy(itemList[index + 1], rec.projectName);
MemPtrUnlock(project);
}
}

LstSetListChoices(lst, itemList, numRecs + 1);
LstDrawList(lst);
}

Thanks,
Steve Warsa

Nov 14 '05 #4

<sw****@msn.com> wrote in message news:11*********************@z14g2000cwz.googlegro ups.com...
Sorry, but I have made changes to the FillProjectList function and I
still receive the error. Here is the modified source for it below:

static void FillProjectList(ListType *lst)
{
UInt16 index;
MemHandle h=0;
UInt16 numRecs = DmNumRecordsInCategory(db, dmAllCategories);
char defaultVal[] = "New...";
itemList = (char **) MemPtrNew((sizeof(char *) * numRecs) + 1);


Are you adding one in the wrong place?
Should that be: ... * (numRecs + 1)); ?

--
John.
Nov 14 '05 #5
sw****@msn.com wrote:
Sorry, but I have made changes to the FillProjectList function and I
still receive the error. Here is the modified source for it below:
Well, there's another rather suspicious looking thing. Let's start with
your typedef (all your code indented to make it more readable)
typedef struct {
char rec[ 1 ];
} PackedProjectDBRecord;
Arrrays with a single element tend to point to trouble... And what do
we find:
static void UnpackProject( ProjectDBRecord *project,
const PackedProjectDBRecord *packedProject )
{
const char *s = packedProject->rec;
project->projectName = s;
s += StrLen( s ) + 1;
project->projectDesc = s;
s += StrLen( s ) + 1;
}
You're using memory that can't be fitting into that type of structure -
the only string you can legally store in a structure of your type
PackedProjectDBRecord is a single, empty string. I don't know if that
has anything to do with your troubles, but it would make sense to think
again what you're doing here - it's not legal C.

On the other hand the lines you specifically pointed out
char defaultVal[ ] = "New...";
itemList = ( char ** ) MemPtrNew( ( sizeof( char * ) * numRecs ) + 1 );
itemList[ 0 ] = (char *) MemPtrNew( StrLen( defaultVal ) + 1 );
StrCopy( itemList[ 0 ], defaultVal );
look reasonable to me, at least under the assumption that memPtrNew()
is equivalent to malloc() and StrCpy() is like strcpy() (but you still
have to check if MemPtrNew() does not return a value that tells you
that you didn't got memory!). In the special case that the first
element of 'itemList' is a string literal you could even use:
char defaultVal[ ] = "New...";
itemList = ( char ** ) MemPtrNew( ( sizeof( char * ) * numRecs ) + 1 );
itemList[ 0 ] = defaultVal;
or just
itemList = ( char ** ) MemPtrNew( ( sizeof( char * ) * numRecs ) + 1 );
itemList[ 0 ] = "New...";


thus avoiding one allocation.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: hall | last post by:
I have a question regarding where memory is allocated when arrays are created. I'll illustrate this by example. I may be wrong on some details, do feel free to correct me. The code piece: int...
11
by: Michael B. Allen | last post by:
Coming from C and Java on *nix I'm a little out of my element messing around with CList and MSVC++ but I think my issues are largely syntactic. I have an ADT that I use called a 'varray' that can...
4
by: Scott Lyons | last post by:
Hey all, Can someone help me figure out how to pass a dynamic array into a function? Its been giving me some trouble, and my textbook of course doesnt cover the issue. Its probably something...
21
by: Matteo Settenvini | last post by:
Ok, I'm quite a newbie, so this question may appear silly. I'm using g++ 3.3.x. I had been taught that an array isn't a lot different from a pointer (in fact you can use the pointer arithmetics to...
10
by: Ian Todd | last post by:
Hi, I am trying to read in a list of data from a file. Each line has a string in its first column. This is what i want to read. I could start by saying char to read in 1000 lines to the array( i...
10
by: Aris | last post by:
A few days ago I asked from you how to join a string like "file" A number that change values from 1 to 5 and another string like ".txt" to have a result like "file1.txt","file2.txt" and so on ...
89
by: scroopy | last post by:
Hi, I've always used std::string but I'm having to use a 3rd party library that returns const char*s. Given: char* pString1 = "Blah "; const char* pString2 = "Blah Blah"; How do I append...
23
by: arnuld | last post by:
i was doing exercise 4.3.1 - 4.29 of "C++ Primer 4/e" where authors, with "run-time shown", claim that C++ Library strings are faster than C-style character strings. i wrote the same programme in...
28
by: hlubenow | last post by:
Hello, I really like Perl and Python for their flexible lists like @a (Perl) and a (Python), where you can easily store lots of strings or even a whole text-file. Now I'm not a...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.