You are not logged in. Please login at www.codechef.com to post your questions!

×

Problem in using malloc function?

int *ptr=malloc(1);
*ptr=100000;
printf("%d",*ptr);

As the parameter we pass to the malloc function is the bytes of memory we want to allocate, but since integer is of 4 bytes the size we pass must be multiple of four to store the integer the values. Here I have passed 1(not a multiple of four) as an argument and still it works fine i.e., the program produces the correct output.

Can anyone explain what is happening here.

asked 07 Jul '16, 20:34

arpit728's gravatar image

1★arpit728
6831968
accept rate: 10%


I think, since ptr is an integer pointer it will always read the next four bytes starting from the address return by malloc . So,there is no problem in storing and dereferencing four bytes.

link

answered 07 Jul '16, 20:47

aka4's gravatar image

4★aka4
161
accept rate: 100%

@aka4 but since memory is allocated to one byte only, and we are trying to access 4 then we should get segmentation fault.

(07 Jul '16, 23:26) arpit7281★

@arpit728 segmentation fault is generated by O.S. when you access an illegal memory. for the smallest program some memory is allocated (may be 2mb for C) .So, it has enough space to accomodate this 4 byte without getting segmentation fault.

(08 Jul '16, 01:22) aka44★

@aka4 If what you are saying is correct then this could should also not give segmentation fault;

int main() {

int *ptr="arpit";

printf("%s",ptr);

}

(08 Jul '16, 08:04) arpit7281★

int *ptr="arpit";

printf("%s",ptr);

This piece of code works perfectly fine because of the implicit type casting by the compiler.The integer pointer is implicitly converted to make it point to the starting memory location of the character buffer.

Malloc works slightly in a different way than expected.

Read this : http://stackoverflow.com/questions/430163/why-does-malloc-allocate-a-different-number-of-bytes-than-requested

Hope this helps.

(Correct me if I went wrong anywhere)

link

answered 08 Jul '16, 08:59

sharad07's gravatar image

4★sharad07
20711
accept rate: 3%

edited 08 Jul '16, 09:01

@sharad07 Dude I am not getting how malloc is working in this scenario.

(09 Jul '16, 01:04) arpit7281★
toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×1,491
×107
×26
×8

question asked: 07 Jul '16, 20:34

question was seen: 994 times

last updated: 09 Jul '16, 01:04