-2

I have allocated memory of 100 MB using malloc

block = (char *)malloc(sizeof(10485760));  // char *block is a global variable

and then I assigned value in block to some local variable say localblock

char *localblock = block;

when I tried to access location after 1 MB and copying string in that location im getting access violation error

int si = 1048576;

for (int i=0; i < si; ++i)
    ++localptr;

strcpy(localblock,"random_string"); <--- im getting error here .please help me

tambre
  • 4,625
  • 4
  • 42
  • 55
imcat
  • 158
  • 6

2 Answers2

3
block = (char *)malloc(sizeof(10485760));

is allocating only sizeof(int) number of bytes, when you access memory beyond that its will end up accessing invalid memory and program might crash

Pras
  • 4,047
  • 10
  • 20
-1

when you use malloc the allocation is not guaranteed.

block = (char *)malloc(sizeof(10485760));is trying to allocate space for 10485760 which is an int - meaning 4/8 bytes on 32/64-bit machine. "random_string" is longer then that, hence your error

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124