473,670 Members | 2,499 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can I do ANYTHING on allocated memory?

Does any of the following constitute undefined behavior? Once I allocate memory,
can I do with it whatever I want (as in the example, use memory allocated as
char *, as memory where I store integers)?

#include <stdio.h>
#include <stdlib.h>

int main(void) {
char *a;
int *x, *y;
a = (char *) malloc(2 * sizeof(int));
// here's the part I'm wondering about
x = (int *) a;
y = (int *) a + sizeof(int);
*x = 10;
*y = 20;
printf ("%d %d\n", *x, *y);
return 0;
}

--
"It is easy in the world to live after the world's opinion; it easy in solitude
to live after our own; but the great man is he who in the midst of the crowd
keeps with perfect sweetness the independence of solitude."
Ralph Waldo Emerson, Self-reliance 1841
http://pinpoint.wordpress.com/

Jan 11 '07 #1
17 1328

"Sourcerer" <en****@MAKNIgm ail.comwrote in message
Does any of the following constitute undefined behavior? Once I allocate
memory, can I do with it whatever I want (as in the example, use memory
allocated as char *, as memory where I store integers)?

#include <stdio.h>
#include <stdlib.h>

int main(void) {
char *a;
int *x, *y;
a = (char *) malloc(2 * sizeof(int));
// here's the part I'm wondering about
x = (int *) a;
y = (int *) a + sizeof(int);
*x = 10;
*y = 20;
printf ("%d %d\n", *x, *y);
return 0;
}
You are playing fast and loose with the C type system.
It is there to help you avoid alignment problems and other nasties, however
for backwards compatibility and certain low-level operations, C also gives
you the freedom to mess about with it.
Technically I think you are OK because pointers to char can be converted to
any other type. This is a hangover from the days when there were no void
pointers, so char *s were used instead.
However had you cast to a short *, and back, it would have been
implentation-defined behaviour. On the vast majority of machines int * and
short *s are the same and the cast is a no op. However it is just possible
that the short * throws some bits away which an int * needs, so a conforming
implementation could do anything it wants in response.
Jan 11 '07 #2
In article <eo**********@s s408.t-com.hr>,
Sourcerer <en****@MAKNIgm ail.comwrote:
>Once I allocate memory,
can I do with it whatever I want (as in the example, use memory allocated as
char *, as memory where I store integers)?
You didn't allocate it as char *:
a = (char *) malloc(2 * sizeof(int));
You just allocated some memory, and (unnecessarily) cast it to char *
before assigning it to a. The memory returned by malloc() doesn't
have a type.

You can store whatever you like in it, provided that it fits and you
respect the alignment rules.
x = (int *) a;
Fine.

But you have a mistake here:
y = (int *) a + sizeof(int);
You have converted a to an integer pointer, then added sizeof(int) to
it. If sizeof(int) is 4, you have just added four int sizes to it,
i.e. 16 bytes. Adding to a pointer adds in units of the size of the
pointed-to object, so you want

y = (int *) (a + sizeof(int));
or
y = (int *) a + 1;

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jan 11 '07 #3
In article <lK************ *********@bt.co m>,
Malcolm McLean <re*******@btin ternet.comwrote :
>You are playing fast and loose with the C type system.
No, apart from his mistake with the addition, he is using pointers
correctly.
>Technically I think you are OK because pointers to char can be converted to
any other type. This is a hangover from the days when there were no void
pointers, so char *s were used instead.
void * has replaced char * as the generic pointer type, but you can't
do arithmetic on void * pointers. char * (or unsigned char *) is the
type used to access memory as bytes, which are the units of C storage.

C guarantees that void * and char * have the same representation, but
the OP is not relying on that.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jan 11 '07 #4
"Sourcerer" <en****@MAKNIgm ail.comwrites:
Does any of the following constitute undefined behavior? Once I
allocate memory, can I do with it whatever I want (as in the example,
use memory allocated as char *, as memory where I store integers)?

#include <stdio.h>
#include <stdlib.h>

int main(void) {
char *a;
int *x, *y;
a = (char *) malloc(2 * sizeof(int));
// here's the part I'm wondering about
x = (int *) a;
y = (int *) a + sizeof(int);
*x = 10;
*y = 20;
printf ("%d %d\n", *x, *y);
return 0;
}
Apart from the addition of sizeof(int), which actually adds
sizeof(int)*siz eof(int) bytes to the pointer, your code looks ok as
far as I can tell. But it could be simplified considerably (and made
more robust):

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int *x, *y;
x = malloc(2 * sizeof *x);
if (x == NULL) {
fprintf(stderr, "malloc failed\n");
exit(EXIT_FAILU RE);
}
y = x + 1;
*x = 10;
*y = 20;
printf ("%d %d\n", *x, *y);
return 0;
}

--
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.
Jan 11 '07 #5
"Richard Tobin" <ri*****@cogsci .ed.ac.ukwrote in message
news:eo******** ***@pc-news.cogsci.ed. ac.uk...
In article <eo**********@s s408.t-com.hr>,
Sourcerer <en****@MAKNIgm ail.comwrote:
>>Once I allocate memory,
can I do with it whatever I want (as in the example, use memory allocated as
char *, as memory where I store integers)?

You didn't allocate it as char *:
>a = (char *) malloc(2 * sizeof(int));

You just allocated some memory, and (unnecessarily) cast it to char *
before assigning it to a. The memory returned by malloc() doesn't
have a type.
Why is the cast unnecessary? malloc() returns void *
You can store whatever you like in it, provided that it fits and you
respect the alignment rules.
>x = (int *) a;

Fine.

But you have a mistake here:
>y = (int *) a + sizeof(int);
Sorry, this should've been y = (int *) (a + sizeof(int));

--
"It is easy in the world to live after the world's opinion; it easy in solitude
to live after our own; but the great man is he who in the midst of the crowd
keeps with perfect sweetness the independence of solitude."
Ralph Waldo Emerson, Self-reliance 1841
http://pinpoint.wordpress.com/

Jan 11 '07 #6
"Sourcerer" <en****@MAKNIgm ail.comwrites:
"Richard Tobin" <ri*****@cogsci .ed.ac.ukwrote in message
news:eo******** ***@pc-news.cogsci.ed. ac.uk...
>In article <eo**********@s s408.t-com.hr>,
Sourcerer <en****@MAKNIgm ail.comwrote:
>>>Once I allocate memory,
can I do with it whatever I want (as in the example, use memory allocated as
char *, as memory where I store integers)?

You didn't allocate it as char *:
>>a = (char *) malloc(2 * sizeof(int));

You just allocated some memory, and (unnecessarily) cast it to char *
before assigning it to a. The memory returned by malloc() doesn't
have a type.

Why is the cast unnecessary? malloc() returns void *
[...]

See question 7.7b in the comp.lang.c FAQ, <http://www.c-faq.com/>.
Questions 7.6, 7.7, and 7.7c are also relevant.

--
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.
Jan 12 '07 #7
Sourcerer wrote:
Does any of the following constitute undefined behavior? Once I allocate
memory, can I do with it whatever I want (as in the example, use memory
allocated as char *, as memory where I store integers)?
Please try to indent code so it is readable. Luckily, your example is
small enough this time, so we can proceed with cleaning that up.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
char *a;
int *x, *y;
a = (char *) malloc(2 * sizeof(int));
^^^^^^^^
This C++-ism is unnecessary and bad practice in C.
// here's the part I'm wondering about
^^
C++-style comments introduced with '//' will not work with C89
compilers, and are a bad idea for code that you post, since your only
protection against line-wrap problems is keeping comments short, as you
have done.
x = (int *) a;
Because malloc returns space suitable aligned for any type, the above
will fly, but
y = (int *) a + sizeof(int);
Did you check to see where this actually pointed? (int *)a is an int
pointer; the next int will be at (int *)a + 1.
*x = 10;
*y = 20;
You may not own the place y currently points.
printf ("%d %d\n", *x, *y);
return 0;
}
Try this modified version of your code to see what the above comments
reflect:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char *a;
int *x, *y;
a = (char *) malloc(2 * sizeof(int));

x = (int *) a;

printf("The pointer-to-char a contains: %p\n"
"The pointer-to-int x = (int *)a contains: %p\n"
"The value of (int *)a + sizeof(int) is %p\n"
"The value of (int *)a + 1 is %p\n",
(void *) a, (void *) x, (void *) ((int *) a + sizeof(int)),
(void *) ((int *) a + 1));

y = (int *) a + sizeof(int);
*x = 10;
#if 0
/* I am not even going to try to assign to *y, as assigned above */
*y = 20;
/* or try to print its value */
printf("%d %d\n", *x, *y);
#endif
/* but this would be ok */
y = x + 1;
*y = 20;
printf("%d %d\n", *x, *y);

return 0;
}
[The results on one implementation]
The pointer-to-char a contains: 20d90
The pointer-to-int x = (int *)a contains: 20d90
The value of (int *)a + sizeof(int) is 20da0
The value of (int *)a + 1 is 20d94
10 20
Jan 12 '07 #8
Richard Tobin well.

Jan 12 '07 #9
On Thu, 11 Jan 2007 22:50:40 -0000, "Malcolm McLean"
<re*******@btin ternet.comwrote in comp.lang.c:
>
"Sourcerer" <en****@MAKNIgm ail.comwrote in message
Does any of the following constitute undefined behavior? Once I allocate
memory, can I do with it whatever I want (as in the example, use memory
allocated as char *, as memory where I store integers)?

#include <stdio.h>
#include <stdlib.h>

int main(void) {
char *a;
int *x, *y;
a = (char *) malloc(2 * sizeof(int));
// here's the part I'm wondering about
x = (int *) a;
y = (int *) a + sizeof(int);
*x = 10;
*y = 20;
printf ("%d %d\n", *x, *y);
return 0;
}
You are playing fast and loose with the C type system.
No, he is not, although he is risking undefined behavior if the
allocation fails and malloc() returns a null pointer, and as others
have pointed out his arithmetic for calculating the value to assign to
'y' is incorrect unless he happens to be on a platform where
sizeof(int) is 1.
It is there to help you avoid alignment problems and other nasties, however
for backwards compatibility and certain low-level operations, C also gives
you the freedom to mess about with it.
Technically I think you are OK because pointers to char can be converted to
any other type. This is a hangover from the days when there were no void
malloc() returns a pointer to void, and pointers to void and to char
are guaranteed to have the same size and representation. So assigning
the returned address to a pointer to char does not change it at all.
pointers, so char *s were used instead.
However had you cast to a short *, and back, it would have been
implentation-defined behaviour. On the vast majority of machines int * and
short *s are the same and the cast is a no op. However it is just possible
that the short * throws some bits away which an int * needs, so a conforming
implementation could do anything it wants in response.
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jan 12 '07 #10

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

Similar topics

73
7993
by: RobertMaas | last post by:
After many years of using LISP, I'm taking a class in Java and finding the two roughly comparable in some ways and very different in other ways. Each has a decent size library of useful utilities as a standard portable part of the core language, the LISP package, and the java.lang package, respectively. Both have big integers, although only LISP has rationals as far as I can tell. Because CL supports keyword arguments, it has a wider range...
3
1383
by: Roubles | last post by:
Hi All, Here's my problem, I have a bunch of code that passes an allocated object (say obj) to a function, and then dereferences that allocated object when the function returns: foo(obj); obj->foobar = TRUE; The issue is that foo *might* free obj. So the dereference can be
6
2310
by: lovecreatesbeauty | last post by:
Hello experts, 1. Does C guarantee the data layout of the memory allocated by malloc function on the heap. I mean, for example, if I allocate a array of 100 elements of structure, can I always reference a correct/valid structure member upon that allocated memory? If I allocate memory, for example like this way:
3
1791
by: Nadav | last post by:
Hi, I am writing a mixed mode application, I have a mixed mode Assembly manipulating a managed byte array, to access this array in unmanaged code I '__pin' the array, As I understand, pining an object guarantee that it will not be collected by the GC ( by increasing it's refcount or so ), Taking that in mind, looking at the code generated by the compiler I can't see anything taking care of the GC refcount... following is the pinned variable...
4
1180
by: gbostock | last post by:
I'm working on some legacy code and came across something like this. Anybody know exactly what the ramifications are to the memory if you do something like this: int somefunction (some arguments) { .... Mystructtype mystruct;
74
4650
by: ballpointpenthief | last post by:
If I have malloc()'ed a pointer and want to read from it as if it were an array, I need to know that I won't be reading past the last index. If this is a pointer to a pointer, a common technique seems to be setting a NULL pointer to the end of the list, and here we know that the allocated memory has been exhausted. All good. When this is a pointer to another type, say int, I could have a variable that records how much memory is being...
26
3050
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I read some of the items from the bottom up of the buffer, and some from the top down, moving the bottom items back to the new re-allocated bottom on every file read. Then when I've read all four files, I sort the top and bottom items separately...
28
2354
by: hijkl | last post by:
hey guys anything wrong with this code?? if it is then what? int *array(int n){ return new int(n); } int main(){ int *p = array(10); for( int i = 0; i < 10; i++ ) {
11
1421
by: xicloid | last post by:
I'm trying to write a program that saves numbers without any duplications. I was thinking I could start by storing the first number in an array with size one, and if the next number is not in the array I've created, I save the first number and the new input number in a new array with size two and delete the first array from memory. This goes on until total of twenty numbers are input into the program. But is it possible to delete...
0
8901
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...
1
8591
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
8660
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
7415
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
5683
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
4390
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2799
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
2
2041
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1792
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.