473,320 Members | 2,145 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,320 software developers and data experts.

Why would malloc() modify the behavior of this output?

If go like the following:

#include <stdlib.h>

void *test_me(int a) {
int *m;
m = &a;
}

main(void){
char *j;

j = test_me(1);

printf("The value of j is : %x", *j);

}

I get:
The value of j is : 1
However, when I add malloc()

#include <stdlib.h>

void *test_me(int a) {
int *m;
m = &a;
}

main(void){
char *p;
char *j;

p = malloc(10);
j = test_me(1);

printf("The value of p is : %x", *p);
printf("The value of j is : %x", *j);

free(p);
}

I get the following:
The value of p is : 0
The value of j is: ffffffc4

Why does p become zero?

Nov 14 '05 #1
14 1456
grocery_stocker wrote:
If go like the following:

#include <stdlib.h>

void *test_me(int a) {
int *m;
m = &a;
Please notice that you're not returning anything from this function,
though its signature indicates a pointer to void will be returned.
Undefined behavior. All bets are off.
}

main(void){
char *j;

j = test_me(1);
Again, since test_me() fails to return anything, the value of `j' is
indeterminate.
printf("The value of j is : %x", *j);

}

I get:
The value of j is : 1
However, when I add malloc()

#include <stdlib.h>

void *test_me(int a) {
int *m;
m = &a;
}

main(void){
char *p;
char *j;

p = malloc(10);
j = test_me(1);

printf("The value of p is : %x", *p);
printf("The value of j is : %x", *j);

free(p);
}

I get the following:
The value of p is : 0
The value of j is: ffffffc4

Why does p become zero?

Undefined behavior means the results could be *anything* -- even nasal
demons might ensue.

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
Nov 14 '05 #2
grocery_stocker wrote:
If go like the following:

#include <stdlib.h>

void *test_me(int a) {
int *m;
m = &a;
}

main(void){
char *j;

j = test_me(1);

printf("The value of j is : %x", *j);

}

I get:
The value of j is : 1
However, when I add malloc()

#include <stdlib.h>

void *test_me(int a) {
int *m;
m = &a;
}

main(void){
char *p;
char *j;

p = malloc(10);
j = test_me(1);

printf("The value of p is : %x", *p);
printf("The value of j is : %x", *j);

free(p);
}

I get the following:
The value of p is : 0
The value of j is: ffffffc4

Why does p become zero?

My guess is that after test_me has been called the stack is corrupt,
since test_me returns an unspecified value, so p is probably modified by
printf.
Nov 14 '05 #3
So in other words, when in the function test_me(), I should have used
'static'?

Nov 14 '05 #4
Groovy hepcat grocery_stocker was jivin' on 10 May 2005 20:10:24 -0700
in comp.lang.c.
Why would malloc() modify the behavior of this output?'s a cool scene!
Dig it!
If go like the following:

#include <stdlib.h>

void *test_me(int a) {
int *m;
m = &a;
}
You should get a diagnostic here. You're not returning anything from
this function. This is no doubt the cause of your problem.
main(void){
int main(void)
{

.... to satisfy C99.
char *j;

j = test_me(1);
j now contains an indeterminate value, because you have failed to
return a value from test_me().
printf("The value of j is : %x", *j);
Since j is indeterminate, dereferencing it here causes undefined
behaviour.

return 0;

.... to satisfy C90.
}

I get:
The value of j is : 1
It could be anything. For that matter, you needn't get any output at
all. The program could crash. Or it could cause a shift in the
space-time continuum which traps you in the 13th dimention. Undefined
behaviour means that ANYTHING the program does is "right".
However, when I add malloc()

#include <stdlib.h>

void *test_me(int a) {
int *m;
m = &a;
}

main(void){
int main(void)
{char *p;
char *j;

p = malloc(10);
Check! Always check the return value of functions like malloc(). You
must not try to dereference the pointer if malloc() fails.
j = test_me(1);

printf("The value of p is : %x", *p);
*p is uninitialised. Its value is indeterminate. p points to
dynamically allocated memory IF the malloc() call succeeded. but the
memory it points to has not been given a value.
printf("The value of j is : %x", *j);
And once again the value of j is indeterminate, and you are causing
undefined behaviour by dereferencing it.
free(p);
return 0;}

I get the following:
The value of p is : 0
The value of j is: ffffffc4

Why does p become zero?


p does not become 0. *p, however, is indeterminate. It could be 0,
but it could be anything else. It just happens to be 0 in this
instance.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
Nov 14 '05 #5
grocery_stocker wrote:
So in other words, when in the function test_me(), I should have used
'static'?

First of all, it is imperative in Usenet discussions to maintain enough
context to know what you're talking about.

And the answer is: The function test_me() needs to return something. It
doesn't.

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays
Nov 14 '05 #6
Peter Shaggy Haywood wrote:
It could be anything. For that matter, you needn't get any output at
all. The program could crash. Or it could cause a shift in the
space-time continuum which traps you in the 13th dimention. Undefined
behaviour means that ANYTHING the program does is "right".


Mankind should try to harness the power of UB.

It seems to have even more potential than nuclear fusion.
Nov 14 '05 #7
Grumble <de*****@kma.eu.org> wrote:
Peter Shaggy Haywood wrote:
It could be anything. For that matter, you needn't get any output at
all. The program could crash. Or it could cause a shift in the
space-time continuum which traps you in the 13th dimention. Undefined
behaviour means that ANYTHING the program does is "right".


Mankind should try to harness the power of UB.

It seems to have even more potential than nuclear fusion.


It does, but unfortunately this includes the power not to be harnessed.
It is a bit like Mephistophilis in this way - people who try to harness
the power of uninitialised objects tend to find themselves facing
thunder and lightning at midnight, twenty-four years being expired.

Richard
Nov 14 '05 #8
"grocery_stocker" <cd*****@gmail.com> writes:
[...]
printf("The value of j is : %x", *j); [...] printf("The value of p is : %x", *p);
printf("The value of j is : %x", *j);


Among numerous other errors, you're not printing the values of j and
p. You're printing the values of *j and *p.

--
Keith Thompson (The_Other_Keith) 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 14 '05 #9
Peter "Shaggy" Haywood wrote:
Groovy hepcat grocery_stocker was jivin':

#include <stdlib.h>

void *test_me(int a) {
int *m;
m = &a;
}
You should get a diagnostic here. You're not returning
anything from this function. This is no doubt the cause
of your problem.


No diagnostic is required for this situation.
int main(void)
{
char *j;

j = test_me(1);


j now contains an indeterminate value, because you have
failed to return a value from test_me().


Actually the behaviour became undefined at the point of
test_me() returning. So 'j' could contain any value
(indeterminate or not), or nasal demons, or cease to exist, etc.
printf("The value of j is : %x", *j);


Since j is indeterminate, dereferencing it here
causes undefined behaviour.


If j were indeterminate, merely mentioning it would cause
undefined behaviour.

Nov 14 '05 #10


grocery_stocker wrote:
So in other words, when in the function test_me(), I should have used
'static'?


That could help matters because I assume this use of the
static keyword is to deal with the function test_me reurning the
address of a int that doesn't exist once the function returns.

But there are numerous other errors. So many that I probably
will miss some in my comments.

The code fails to include header stdio.h.

Function main returns a int.

Tbe function test_me code does not return a value even though
the prototype calls for a return of void *.

You are attempting to convert a int * to void * to char *.
This does not guarantee that the original pointer(to int *)
will compare equal to the result(char *).
If you converted it back again to int * (int * -> void * -< int *),
the the standard says the result shall compare equal to the
original pointer.

If you rid all this UB then you will see that function
malloc will have no affect on the test.

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

void *test_me(int a)
{
static int m;
m = a;
return &m;
}

int main(void)
{
int *j, *i;

j = test_me(1);
printf("Test on function test-me before malloc\n"
"The value of j is : %i\n"
"The address of is %x\n\n", *j, (void *)j);
i = malloc(10 * sizeof *i);
printf( "Test on function test_me after malloc\n"
"The value of j is : %d\n"
"The address of is %x\n\n", *j, (void *)j);
free(i);
return 0;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #11


grocery_stocker wrote:
So in other words, when in the function test_me(), I should have used
'static'?


That could help matters because I assume this use of the
static keyword is to deal with the function test_me reurning the
address of a int that doesn't exist once the function returns.

But there are numerous other errors. So many that I probably
will miss some in my comments.

The code fails to include header stdio.h.

Function main returns a int.

Tbe function test_me code does not return a value even though
the prototype calls for a return of void *.

You are attempting to convert a int * to void * to char *.
This does not guarantee that the original pointer(to int *)
will compare equal to the result(char *).
If you converted it back again to int * (int * -> void * -< int *),
the the standard says the result shall compare equal to the
original pointer.

If you rid all this UB then you will see that function
malloc will have no affect on the test.

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

void *test_me(int a)
{
static int m;
m = a;
return &m;
}

int main(void)
{
int *j, *i;

j = test_me(1);
printf("Test on function test-me before malloc\n"
"The value of j is : %d\n"
"The address of is %p\n\n", *j, (void *)j);
i = malloc(10 * sizeof *i);
printf( "Test on function test_me after malloc\n"
"The value of j is : %d\n"
"The address of is %p\n\n", *j, (void *)j);
free(i);
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #12
On 11 May 2005 04:15:21 -0700, in comp.lang.c , "Old Wolf"
<ol*****@inspire.net.nz> wrote:
Peter "Shaggy" Haywood wrote:
Groovy hepcat grocery_stocker was jivin':
>
>#include <stdlib.h>
>
>void *test_me(int a) {
>int *m;
>m = &a;
>}


You should get a diagnostic here. You're not returning
anything from this function. This is no doubt the cause
of your problem.


No diagnostic is required for this situation.


possibly, but any decent compiler should emit one anyway.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
Nov 14 '05 #13
On Wed, 11 May 2005 12:16:11 -0400, Al Bowers wrote:

....
You are attempting to convert a int * to void * to char *.
This does not guarantee that the original pointer(to int *)
will compare equal to the result(char *).
In order to compare values they have to be of the same type. Once you
ensure that the situation changes.

One of the main probmes with the original code is the incorrect way that
it attempts to convert the values of pointers (presuming that was
intended). Your version fixes that.
If you converted it back again to int * (int * -> void * -< int *),
the the standard says the result shall compare equal to the
original pointer.


In this case there's int * -> void * -> char * vs. int * -> char *. Given
that void * has the same representation as pointers to character types it
is difficult to see how these conversion sequences could produce unequal
results from a valid initial value.

Lawrence
Nov 14 '05 #14
Lawrence Kirby wrote:

On Wed, 11 May 2005 12:16:11 -0400, Al Bowers wrote:

...
You are attempting to convert a int * to void * to char *.
This does not guarantee that the original pointer(to int *)
will compare equal to the result(char *).


In order to compare values they have to be of the same type. Once you
ensure that the situation changes.

One of the main probmes with the original code
is the incorrect way that
it attempts to convert the values of pointers (presuming that was
intended). Your version fixes that.
If you converted it back again to int * (int * -> void * -< int *),
the the standard says the result shall compare equal to the
original pointer.


In this case there's int * -> void * -> char * vs. int * -> char *.
Given that void * has the same representation as pointers
to character types it
is difficult to see how these conversion sequences
could produce unequal results from a valid initial value.


There's also that
a pointer to an object, converted to (char *),
becomes a pointer to the lowest addressable byte of the object.
So, even if a (void *) pointer
didn't have any special relation to (char *),
converting a (void *) to (char *),
should yield the address of the lowest addressable byte
of whatever object the (void *) pointer has the address of.

For
int object;
(char *)&object is the address of the lowest addressable byte of object.
(char *)(void *)&object, should be the address of the same byte.

I don't think pointer representation is an issue here.

--
pete
Nov 14 '05 #15

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

Similar topics

9
by: WL | last post by:
Hey, all. I'm creating an array of strings (char **argv style) on the fly, and using realloc to create string pointers, and malloc for the strings itself (if that makes any sense). I'm using the...
9
by: Pegboy | last post by:
I need three buffers and am going to allocate memory for them, is it legal to allocate and free the required memory with one call to malloc and free? unsigned char *b1, *b2, *b3; if( (b1 =...
11
by: Gustavo G. Rondina | last post by:
Hi all I'm writting a simple code to solve an ACM problem (http://acm.uva.es, it is the problem #468). In its code I have the following fragment: freq = calcfreq(hashfreq, strfreq, input);...
7
by: Fatted | last post by:
I'm trying to learn how to create arrays dynamically. But its just not happening. Have a look at code below and point and laugh where appropriate... First part of program, I'm using an array of...
58
by: lasek | last post by:
Hi all..i'm here another time..for a simple question: #include <stdlib.h> #include <stdio.h> int main(void) { /* ** I know that someone else use different malloc ** instruction
36
by: Martin Andert | last post by:
Hello, I have a question regarding malloc and free. Here my code sample: int main() { /* allocating dynamic memory for array */ int* array = (int*) malloc(5 * sizeof(int)); /* ... program...
54
by: Neo | last post by:
Hi Folks, I've a simple qestion related to dynamic memory allocation in C here is the code: #include <stdio.h> int main() {
15
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that...
68
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting;...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.