473,783 Members | 2,317 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory Allocating problem

Hi all ,
I am beginner to C programming. I have a defined astructure like the
following, and i am using aliases for the different data types in the
structure,

typedef struct _NAME_INFO {
struct _NAME_INFO *Next;
ULONG LastId;
ULONG Id;
PVOID Value;
BOOLEAN Used;
USHORT CodePage;
WCHAR *Name;
} NAME_INFO, *PNAME_INFO;

When I allocate memory to the defined structure, in the following way,

p = (PNAME_INFO)mal loc(sizeof(PNAM E_INFO)+ (wcslen(Name) + 1 ) *
sizeof( WCHAR ));
p->Name = (WCHAR *) malloc(( wcslen(Name) + 1 ) * sizeof( WCHAR ));
It core dumps when allocating memory to the pointer to wide character
*Name. Can somebody explain how to overcome this problem.

Thanks in Advance

Prasanna Bhat Mavinkuli

Nov 15 '05 #1
7 2098
I think you should replace sizeof(PNAME_IN FO) to sizeof(NAME_INF O).

Nov 15 '05 #2


bo*******@yahoo .co.in wrote:
Hi all ,
I am beginner to C programming. I have a defined astructure like the
following, and i am using aliases for the different data types in the
structure,

typedef struct _NAME_INFO {
struct _NAME_INFO *Next;
ULONG LastId;
ULONG Id;
PVOID Value;
BOOLEAN Used;
USHORT CodePage;
WCHAR *Name;
} NAME_INFO, *PNAME_INFO;

When I allocate memory to the defined structure, in the following way,

p = (PNAME_INFO)mal loc(sizeof(PNAM E_INFO)+ (wcslen(Name) + 1 ) *
sizeof( WCHAR ));
1. remove the cast and include stdlib.h
2. use p = malloc(sizeof(N AME_INFO));
3. verify p is not NULL before using.
p->Name = (WCHAR *) malloc(( wcslen(Name) + 1 ) * sizeof( WCHAR ));
It core dumps when allocating memory to the pointer to wide character
*Name. Can somebody explain how to overcome this problem.

Thanks in Advance

Prasanna Bhat Mavinkuli


Nov 15 '05 #3
Rajan wrote:

I think you should replace sizeof(PNAME_IN FO) to sizeof(NAME_INF O).


I think you should replace your newsreader with something that can
create proper quotes, or should pay attention to my sig below.
What you wrote is useless in isolation.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 15 '05 #4
bo*******@yahoo .co.in wrote:

I am beginner to C programming. I have a defined astructure like
the following, and i am using aliases for the different data types
in the structure,

typedef struct _NAME_INFO {
struct _NAME_INFO *Next;
ULONG LastId;
ULONG Id;
PVOID Value;
BOOLEAN Used;
USHORT CodePage;
WCHAR *Name;
} NAME_INFO, *PNAME_INFO;

When I allocate memory to the defined structure, in the following way,

p = (PNAME_INFO)mal loc(sizeof(PNAM E_INFO)+ (wcslen(Name) + 1 ) * sizeof( WCHAR ));
p->Name = (WCHAR *) malloc(( wcslen(Name) + 1 ) * sizeof( WCHAR ));
It core dumps when allocating memory to the pointer to wide character
*Name. Can somebody explain how to overcome this problem.


Try writing:

if (NULL == (p = malloc(sizeof *p))) {
/* take corrective action, no memory */;
}
else if (NULL ==
(p->Name = malloc((sizeof *(p->Name)) * (1+wcslen(Name) )) {
/* take corrective action, no memory */
}
else {
/* allocations successful, enjoy */
}

The only thing that has a need for a varying length is the Name
field. The only thing the casts are doing for you is suppressing
helpful compiler error messages. You didn't show the declaration
for Name, so that may also be uninitialized.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 15 '05 #5
bo*******@yahoo .co.in writes:
I am beginner to C programming. I have a defined astructure like the
following, and i am using aliases for the different data types in the
structure,

typedef struct _NAME_INFO {
struct _NAME_INFO *Next;
ULONG LastId;
ULONG Id;
PVOID Value;
BOOLEAN Used;
USHORT CodePage;
WCHAR *Name;
} NAME_INFO, *PNAME_INFO;
Why are you using all these aliases? If PVOID is supposed to be a
pointer to void, just use void*; if it isn't, the name PVOID is
misleading.

There's some debate as to whether typedefs for structs are a good
idea. Some argue that just using "struct foo" directly is clearer
than using a typedef name. A typedef hides the fact that the type is
a struct. There are cases where you want to do this (e.g., the type
FILE in <stdio.h>), but this isn't such a case.

The name _NAME_INFO is potentially a problem. Many identifiers
starting with an underscore are reserved to the implementation. (The
rule is a bit more complicated, and has to do with what character
follows the initial underscore, but it's best to avoid declaring
things with leading underscores altogether.)

If you're using a C99 compiler, you can use type "bool" if you have
"#include <stdbool.h>". Otherwise, you can define type "bool"
yourself. One approach is:

#if __STDC_VERSION_ _ >= 199901L
#include <stdbool.h>
#else
typedef int bool; /* or typedef char bool; */
#define false 0
#define true 1
#endif

So, given the above definition of "bool", and assuming I'm guessing
correctly what your aliases mean, and assuming "#include <stddef.h>"
for the definition of wchar_t, I'd declare your structure as follows:

struct Name_Info {
struct name_info *Next;
unsigned long LastId;
unsigned long Id;
void *Value;
bool Used;
unsigned short CodePage;
wchar_t *Name;
};

If you want to be able to refer to the type as "Name_Info" rather than
"struct Name_Info", you can do this:

typedef struct Name_Info {
/* member declarations as above */
} Name_Info;

Structure tags and typedef names are in separate namespaces, so
there's no need to use distinct identifiers. However, I probably
wouldn't bother with the typedef; instead, I'd use "struct Name_Info"
directly.

I definitely wouldn't create a typedef for a pointer to a struct
Name_Info. Hiding the fact that something is a pointer is likely to
cause confusion.
When I allocate memory to the defined structure, in the following way,

p = (PNAME_INFO)mal loc(sizeof(PNAM E_INFO)+ (wcslen(Name) + 1 ) *
sizeof( WCHAR ));
p->Name = (WCHAR *) malloc(( wcslen(Name) + 1 ) * sizeof( WCHAR ));
It core dumps when allocating memory to the pointer to wide character
*Name. Can somebody explain how to overcome this problem.


If you're allocating an object of type "struct Name_Info", you just
want to allocate the size of the struct. You could possibly allocate
a "struct Name_Info" and the wide string to be pointed to by the Name
member in a single chunk, but getting the alignment right would be
difficult -- and since you're allocating space for p->Name separately,
that's obviously not what you're trying to do anyway.

Casting the result of malloc() is unnecessary and can mask the error
of forgetting the "#include <stdlib.h>".

So here's how I'd do the allocations:

Name_Info *p;
p = malloc(sizeof *p);
if (p == NULL) {
/* error handling */
}
p->Name = malloc((wcslen( Name) + 1) * sizeof wchar_t);
if (p->Name == NULL) {
/* error handling */
}

In the first malloc(), note that the argument is "sizeof *p". By
referring to the pointer object and not to its type, we avoid problems
if the type is changed later on. Since the expression "*p" is the
operand of a sizeof, it's not evaluated; it's used only to determine
the size of the type p points to -- which is exactly what we want.

I'm assuming that the error handling code will bail out of whatever
context you're in, so you won't attempt to assign to p->Name unless
you know that the allocation for p has already succeeded.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #6


bo*******@yahoo .co.in wrote:
Hi all ,
I am beginner to C programming. I have a defined astructure like the
following, and i am using aliases for the different data types in the
structure,

Unless you have a really good reason for using typedef names for
primitive data types (for example, you know USHORT will *always* be a
particular size), use the regular type names, i.e., change
typedef struct _NAME_INFO {
struct _NAME_INFO *Next;
ULONG LastId;
ULONG Id;
PVOID Value;
BOOLEAN Used;
USHORT CodePage;
WCHAR *Name;
} NAME_INFO, *PNAME_INFO;

to

typedef struct NAME_INFO { // don't use leading underscore
struct NAME_INFO *Next;
unsigned long LastId;
unsigned long Id;
void *Value; // I'm assuming PVOID == void*
bool Used; // assuming bool type is available; otherwise int will
work
unsigned short CodePage;
wchar_t *Name;
} NAME_INFO;

While I'll argue with Keith over the virtue of creating a typedef name
for the struct type (I do it all the time, but I also create accessor
functions to do member assignments), I won't argue about creating a
typedef name for pointer types; don't do it. It will just cause
heartburn. I know there are a lot of examples of the practice,
especially in MS Windows code, but it winds up causing more problems
than it allegedly solves.

Just use NAME_INFO* when you need a pointer.
When I allocate memory to the defined structure, in the following way,

p = (PNAME_INFO)mal loc(sizeof(PNAM E_INFO)+ (wcslen(Name) + 1 ) *
sizeof( WCHAR ));
p->Name = (WCHAR *) malloc(( wcslen(Name) + 1 ) * sizeof( WCHAR ));
It core dumps when allocating memory to the pointer to wide character
*Name. Can somebody explain how to overcome this problem.

You're allocating p incorrectly. Use the following (assuming p is type
NAME_INFO *):

p = malloc(sizeof *p);

Note that I'm using sizeof on the actual object I'm allocating to, not
its type. Also notice I'm not casting the result of malloc(). You
don't need to cast, and doing so can mask a compile time error if you
forget to #include <stdlib.h>.

To allocate the Name member, do the following.

if (p) // make sure p was successfully allocated
{
p->Name = malloc(sizeof *(p->Name) * wcslen(Name));
}
Thanks in Advance

Prasanna Bhat Mavinkuli


Nov 15 '05 #7
"John Bode" <jo*******@my-deja.com> writes:
[snip]
Unless you have a really good reason for using typedef names for
primitive data types (for example, you know USHORT will *always* be a
particular size), use the regular type names, i.e., change


To expand on that a bit, USHORT is obviously an abbreviation for
"unsigned short". If it *is* unsigned short, it's much clearer to use
unsigned short directly. If it *isn't* unsigned short, the name is
grossly misleading.

If you specifically want, say, a 16-bit unsigned type, a name like
"uint16_t" is much clearer (and that's exactly the name used in C99's
<stdint.h>). But be aware that not all implementations necessarily
have a 16-bit unsigned type.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #8

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

Similar topics

4
3853
by: Greg Baker | last post by:
I don't know what standard protocol is in this newsgroup. Am I allowed to post code and ask for help? I hope so.. :) Here's my problem: I am trying problem 127 of the valladolid online contests (http://online-judge.uva.es/p/v1/127.html). The program I wrote seems to work fine, but it takes way too much memory to run. I am not that good at programming C++, unfortunately, so I can't seem to find my memory leak. As far as I can tell,...
32
3865
by: John | last post by:
Hi all: When I run my code, I find that the memory that the code uses keeps increasing. I have a PC with 2G RAM running Debian linux. The code consumes 1.5G memory by the time it finishes execution. But I do not think it needs so much memory. About 500M memory should be enough. I have following questions about memory leak. (1).If in my code I only define constructor for my class, and do not define destructor, will it cause memory leak?
4
745
by: Sameer | last post by:
Hello Group, This is one problem in programming that is troubling me. there is a segmentation fault just before creating memory to a structure ..i.e, just after the "allocating memory " statement. This happens for some inputs and not all. What can be the reason for such fault ?
11
2860
by: William Buch | last post by:
I have a strange problem. The code isn't written by me, but uses the qsort function in stdlib. ALWAYS, the fourth time through, the memory location of variable list (i.e. mem location = 41813698) becomes 11, then the program crashes. It is obviously qsort that may me overwritten the used memory location. The weird thing is that it is ALWAYS the fourth time running the program. Below is the code MEMORY LOCATION OK HERE for (i = 0; i...
2
3277
by: Mike | last post by:
Hi, I am new to C and having problems with the following program. Basically I am trying to read some files, loading data structures into memory for latter searching. I am trying to use structres and arrays of pointers to them. I have gotten the program to compile with gcc on WinXP. If the file i read doesnt have alot of records, it runs thru. But once i add more, it dies. In this program i have 4 files setup to read. The
9
4538
by: Hemal | last post by:
Hi All, I need to know the memory required by a c program. Is there any tool/utility which can give me the memory usage in terms of DATA segment, TEXT segment, BSS segment etc. I am working on linux platform and my target is ARM processor. But i guess it should not matter. Actually i need to know both RAM & ROM usage.
5
2681
by: Mahendra Kumar Kutare | last post by:
I am trying to implement a webserver with boss-worker model thread pool implementation - I have a header declaration threadpool.h as - typedef struct threadpool_work { void (*routine) (); void *arg; struct threadpool_work *next; } threadpool_work_t;
6
4158
by: tgnelson85 | last post by:
Hello, C question here (running on Linux, though there should be no platform specific code). After reading through a few examples, and following one in a book, for linked lists i thought i would try my own small program. The problem is, I seem to be having trouble with memory, i.e. sometimes my program will work and display the correct output, and sometimes it will not and display garbage (in a printf call) so i assume i have been using...
10
1768
by: Chris Saunders | last post by:
Here is the declaration of a struct from WinIoCtl.h: // // Structures for FSCTL_TXFS_READ_BACKUP_INFORMATION // typedef struct _TXFS_READ_BACKUP_INFORMATION_OUT { union { //
0
9480
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
10313
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
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
10081
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
9946
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
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
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
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

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.