I get a runtime error while trying to run the code below.
- The function get() returns a void pointer where the user input is stored.
- The function getShort() calls the get() function and typecasts and dereferences the pointer to short before returning its value.
- While the value works perfectly fine inside getShort(); any other method that call it will get the following runtime error.
The instruction at Ox000000000040002C referenced memory at Ox000000000000002C. The memory could not be written.
void * get(char formatSpecifier[]){
void *ptr;
scanf(formatSpecifier, ptr);
return ptr;
}
int getInt(){
int i = *(int *)get("%d");
printf("Works perfectly fine here: %d", i);
return i;
}
int main(){
int j = getInt(); // Error thrown here.
prinf("The value is : %d", j); // Does not print;
return 0;
}
Any help or feedback is appreciated. Many thanks.
CodePudding user response:
As n. m. said, at line 3 inside scanf(formatSpecifier, ptr);
you use an uninitialized pointer. void *ptr;
was not initialized, it means that you didn't decide where it points to, but then tried to use it, trying to write on inaccessible memory as your error
The instruction at Ox000000000040002C referenced memory at Ox000000000000002C. The memory could not be written.
points out. In this case Ox000000000040002C is the index of your ptr, while Ox000000000000002C is the index it was pointing to(it can vary since you didn't initialize your pointer).
I believe you can read more on this here.
Side note: In your question you explained a function GetShort() but used a function GetInt() in the code provided.