pirox22
pirox22

Reputation: 922

Dynamic char array

Trying to allocate a char array of N elements.

#include <stdio.h>
#include <malloc.h>

int main()
{
     int N = 2;

     char *array = malloc(N * sizeof(char)); 

     array[0] = 'a';
     array[1] = 'b';
     array[2] = 'c';    // why can i do that??

     printf("%c", array[0]);
     printf("%c", array[1]);
     printf("%c", array[2]);  //shouldn't I get a seg fault here??

     return 0;
 }

The question is:

Since I am allocating 2 * 1 = 2 bytes of memory that means i can have 2 chars in my array. How is it possible that I have more?? I also printed sizeof(*array) and it prints 8 bytes. What am I missing here?

Upvotes: 0

Views: 1490

Answers (2)

Shirish Hirekodi
Shirish Hirekodi

Reputation: 412

The 0th and 1th elements are inside of valid memory allocation. With the 2th element you have trespassed into unallocated memory. Will work fine, until that part of the memory gets allocated for something else, then your 2th element will start having crazy values. Your code will go nuts. But as @jon pointed out, the compiler is supposed to be catching this, unless you have asked it to shutup

Upvotes: 0

isedev
isedev

Reputation: 19641

A segmentation fault occurs when a program tries to access a memory address which has not been mapped by the operating system into its virtual memory address space.

Memory allocation occurs in pages (usually 4k or 8k, but you can get larger pages too). So the malloc() call gets a memory page from the OS and carves off a piece of it for the array and returns a pointer to that. In this specific case, there is still a large piece of the page remaining after your array (unallocated but already available for use with subsequent calls to malloc()) - array[2] references a valid address within the page, so no segmentation fault.

However, you are accessing memory beyond the array and as mentioned in the comments, that is undefined behaviour and would probably cause memory corruption in a larger program by overwritting the value of unrelated variables.

Upvotes: 2

Related Questions