473,591 Members | 2,871 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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:

*************** *************** *************** *************** ******
LstSetListChoic es 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 LstSetListChoic es (
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];
} PackedProjectDB Record;

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 = DmNumRecordsInC ategory(db, dmAllCategories );
char defaultVal[] = "New...";
itemList = (char **) MemPtrNew((size of(char *) * numRecs) + 1);
itemList[0] = (char *) MemPtrNew(sizeo f(defaultVal));
StrCopy(itemLis t[0], defaultVal);

for(index = 0; index < numRecs; index++)
{
// get the handle to the record and set busy bit
h = DmQueryRecord(d b, index);
if (h) { // could fail due to insufficient memory!
PackedProjectDB Record *project = MemHandleLock(h );
ProjectDBRecord rec;
UnpackProject(& rec, project);
printf("Here is the project name: %s", rec.projectName );
itemList[index + 1] = (char *)
MemPtrNew(StrLe n(rec.projectNa me));
StrCopy(itemLis t[index + 1], rec.projectName );
MemPtrUnlock(pr oject);
}
}

LstSetListChoic es(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(sizeo f(defaultVal));
StrCopy(itemLis t[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(Pro jectDBRecord *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(MemHandleRes ize(projectDBHa ndle, length) == 0)
{
// copy the fields
s = MemHandleLock(p rojectDBHandle) ;
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 (projectDBHandl e);
}
}

static void UnpackProject(P rojectDBRecord *project, const
PackedProjectDB Record *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 3744
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 = DmNumRecordsInC ategory(db, dmAllCategories );
char defaultVal[] = "New...";
itemList = (char **) MemPtrNew((size of(char *) * numRecs) + 1);
itemList[0] = (char *) MemPtrNew(sizeo f(defaultVal));
StrCopy(itemLis t[0], defaultVal); for(index = 0; index < numRecs; index++)
{
// get the handle to the record and set busy bit
h = DmQueryRecord(d b, index);
if (h) { // could fail due to insufficient memory!
PackedProjectDB Record *project = MemHandleLock(h );
ProjectDBRecord rec;
UnpackProject(& rec, project);
printf("Here is the project name: %s", rec.projectName );
itemList[index + 1] = (char *)
MemPtrNew(StrLe n(rec.projectNa me));
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(itemLis t[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***********@p hysik.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 = DmNumRecordsInC ategory(db, dmAllCategories );
char defaultVal[] = "New...";
itemList = (char **) MemPtrNew((size of(char *) * numRecs) + 1);
itemList[0] = (char *) MemPtrNew(StrLe n(defaultVal) + 1);
StrCopy(itemLis t[0], defaultVal);

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

// do something with the record's contents here
itemList[index + 1] = (char *)
MemPtrNew(StrLe n(rec.projectNa me) + 1);
StrCopy(itemLis t[index + 1], rec.projectName );
MemPtrUnlock(pr oject);
}
}

LstSetListChoic es(lst, itemList, numRecs + 1);
LstDrawList(lst );
}

Thanks,
Steve Warsa

Nov 14 '05 #4

<sw****@msn.com > wrote in message news:11******** *************@z 14g2000cwz.goog legroups.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 = DmNumRecordsInC ategory(db, dmAllCategories );
char defaultVal[] = "New...";
itemList = (char **) MemPtrNew((size of(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 ];
} PackedProjectDB Record;
Arrrays with a single element tend to point to trouble... And what do
we find:
static void UnpackProject( ProjectDBRecord *project,
const PackedProjectDB Record *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
PackedProjectDB Record 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***********@p hysik.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
5333
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 p; Creates a 2dimensional array. p can be thought of as a pointer, containing the adres of the first element in the array. The memory is
11
8686
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 return a pointer to an arbirary sized element in an array given an index and it will allocate the memory to back it if necessary: struct varray *tests = varray_new(sizeof(struct test)); struct test *t = (struct test *)varray_get(tests, 50));
4
7670
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 simple, but its just not popping into my mind at the moment. My little snippet of code is below. Basically, the studentID array is dynamic so it will fit any length of a Student's Name. What I'm trying to do is place this chunk of code into a...
21
3911
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 "browse" it). So I expected that when I run this program, I get both c1.A and c2.A pointing to the same address, and changing c1.A means that also c2.A changes too. ----- BEGIN example CODE -----------
10
9004
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 think!!). But I want to use malloc. Each string is at most 50 characters long, and there may be zero to thousands of lines. How do I actually start the array? I have seen char **array etc. At first I tried char *array but I think that gives 50...
10
1502
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 and you gave me the right answer. But now I got another problem.
89
5106
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 the contents of pString2 to pString? (giving "Blah Blah Blah")
23
2937
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 C & hence found that claim of the authors is *partial*. If we use C-style strings in C++ instead of Library String class, then they are slow but if write the same programme in C then C strings are "faster" than both C++ Library strings & C-style...
28
6030
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 C-professional, just a hobby-programmer trying to teach it myself. I found C rather difficult without those lists (and corresponding string-functions). Slowly getting into C-strings, I thought, what if I take a C-string and
0
7934
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7870
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8362
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7992
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6639
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3850
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3891
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2378
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1465
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.