Unhandled exception at 0x00c71443 0xC0000005: Access violation writing location 0x00000028

-4

I was writing C code to simulate transmitting a character from uart. I am getting the title error.

Code:

#include<stdio.h>
void transmit(char uart, char data[]){
   writeReg(uart,data);
      ......
       ......
}

void writeReg(char addr, char data[]){
  char* dataPtr = data;
  char* regPtr = (char*)addr;
  *regPtr = *dataPtr;  ........ This is where the error was thrown <bad ptr>
}

void main(){
   transmit(0x28,"1245");
}
c
asked on Stack Overflow Jul 12, 2014 by user3833065

3 Answers

5

Your code attempts to write to memory at the location 0x00000028. This address is in a protected region of the address space and you are not allowed to write (or read) there. Hence the access violation.

Your problems begin here:

char* regPtr = (char*)addr;

addr is a char, and in your program it has the value 0x28. You then treat that as an address, and the inevitable consequence is the access violation.

The reason the compiler rejected

char* regPtr = addr;

is that addr is not a char*. Simply casting does not change that fact. When you are faced with a compilation error that you do not understand, do not attempt to cast your way past it. Step 1 is always to understand the error.

Your code makes no real sense. I don't know what it tries to do, so I cannot tell you what the code should be.

answered on Stack Overflow Jul 12, 2014 by David Heffernan • edited Jul 12, 2014 by David Heffernan
2

You are casting a character value to a pointer, which gives you an invalid pointer.

Perhaps you wanted to do this instead?

char *regPtr = &addr;
answered on Stack Overflow Jul 12, 2014 by Felix Frank
1

You are trying to write in the memory location that is not allocated to your program.

Your program must change values in memory contained only to the address space allocated to it.

Allocation of address space is done dynamically and you should always use relative memory location and not absolute location, like in your case. Because relative memory location will shift according to the address space allocated to your program, but absolute location

may or may not fall

in it, which may produce exceptions like it did.

answered on Stack Overflow Jul 12, 2014 by Himanshu Tyagi • edited Jul 12, 2014 by Himanshu Tyagi

User contributions licensed under CC BY-SA 3.0