-3

if is it possible run-time bad pointer exception in C language?.

I am using below compiler.

Note : Microsoft Visual C++ Compiler

Sample Programs Below.

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <Windef.h>

typedef struct tagTest{
int i;
char *str;
}   Test, 
    FAR *LPTest, 
    FAR **LLPTEST;

 extern LLPTEST m;

 int main()
 {

  int i;

  LLPTEST m = NULL;

  m = (LLPTEST)malloc(sizeof(LLPTEST));

  // Here We Check m[0] memory allocated or not ?
  // example: if(m[0]), or if(m[0]->i) any other idea. here m[0] is CXX0030 error expression cannot be evaluated.

  /* allocate memory */
  for(i=0; i<10; i++)
  {
     m[i] = (LPTest) malloc(sizeof(Test));
     m[i]->i = i;
     m[i]->str = (char*) malloc(10*sizeof(char));
     m[i]->str = "Test";
 }

 return 0;
}
Vijay Kumbhani
  • 734
  • 1
  • 6
  • 26

3 Answers3

3

No. C doesn't support exceptions, so there's nothing to catch. What you're seeing isn't a "bad pointer exception," it's a memory access error -- there is no way to recover from it.

Patrick Collins
  • 10,306
  • 5
  • 30
  • 69
3

You have several problems in your code. Here's a list of some of them:

  • Don't cast the return of malloc
  • For m you allocate sizeof(LLPTEST) bytes, but you should really allocate sizeof(LPTest)
  • Continuing the previous point, you only allocate one pointer, so only m[0] is valid, all other indexes will cause you to write out of bounds. You should do e.g.

    m = malloc(sizeof(LPTest) * 10);
    

    This point is the cause of your problems, as it causes undefined behavior

  • You allocate memory for m[i]->str, but then you overwrite that pointer with a pointer to a string literal, thereby loosing the pointer to the allocated memory (i.e. you have a memory leak)

  • Continuing the previous point, because m[i]->str now points to a string literal, and not something you allocated yourself, you can not free this pointer
  • No error checking, remember that malloc can fail

If you don't know how many items you need to allocate for m beforehand, you can use realloc to reallocate with a larger size.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Some exceptions can catch MSVC is to extend the syntax.

#include <windows.h>
#include <stdio.h>

typedef struct tagTest{
    int i;
    char *str;
} Test;

int main(){
    Test *m;
    //m = malloc(sizeof(Test));//it can be avoided by examining whether NULL simply.
    m = NULL;//malloc is unable to allocate memory
    __try{
        m->i = 0;//exception occurs
        m->str = "Test";
    }
    __except(EXCEPTION_EXECUTE_HANDLER){
        if(EXCEPTION_ACCESS_VIOLATION==GetExceptionCode())
            puts("ACCESS VIOLATION");
        puts("EXCEPTION OCCURRED");
    }
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70