简体   繁体   中英

Crashing code(pointers C99)

I am trying to understand why that code crash:(CodeBlocks C99)

int a;
int **b=0;
*b=&a;

I know that * b is of type int* and &a is also int* so what's the problem here?

Let's take this apart:

int a; /* make a an integer, assuming this is in a function on the stack */
int **b=0; /* make b a pointer to a pointer to an integer, but make it point to 0 */
*b=&a; /* store the address of a at the address pointed to by b, which is 0 */

IE you are explicitly writing the address of a to a zero location. The problem is not type compatibility, it's that you are trying to store something at location zero, which will cause a seg fault.

To fix it do something like:

int a; /* make a an integer, assuming this is in a function on the stack */
int *c = 0; /* make an integer pointer, initialise it to NULL */
int **b=&c; /* make b a pointer to a pointer to an integer, make it point to c */
*b=&a; /* store the address of a at the address pointed to by b, which is c */

b指向一个指针,您将指针指向0 / NULL,这意味着当您执行* b =您正在将值分配给地址0时,它将在大多数OS上消失(在嵌入式系统上,这取决于处理器)

You are dereferencing the NULL-Pointer. b points to NULL and in the next line you are dereferencing it and assigning it a new value.

You are not allowed to write to memory you don't own, and you are especially not allowed to write to NULL.

You cannot set pointers to values like that (*b=&a) because they are at the time not pointing to anything; in order to set their value they must be pointing to something.

int a;
int *tmp;
int **b = &tmp;
*b = &a; //this should work because you are setting a real variable (in this case tmp) to &a

Your int **b=0 is a pointer to int * , that is initialized to NULL , and isn't pointing at an allocated storage area. When you write to *b , you are attempting to dereference a null pointer, which is illegal.

If you were to allocate storage, for example using b=malloc(sizeof(*b)) , you would then be able to write into the area pointer at by b using *b=&a , because then *b would be a valid address to write into.

#include <stdlib.h>

int
main()
{
  int a;
  int **b = (int**)malloc(1 * sizeof(int));
  *b = &a;
  free(b);
  return 0;
}

Your *b = &a has the same effect of b[0] = &a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM