(C/C++) ERROR: Thread 1: EXC_BAD_ACCESS (code=2, address=0x....)

Xcode version V13.2.1

The problem is the same as the title, first introduce a solution that is ridiculously wrong
: (The steps come from a blog)



The function of this method isdebug off, in other wordsThis method "fixes" any error

solution:

Back to the topic, EXC_BAD_ACCESSthis kind of error is likely to be a problem with the code itself, usually becauseThe system accesses a memory area that has been freed, for example in the following code:

  1. Define a structure Node(node), each node object can point to another node, thus forming a node chain
  2. Define the initialization function InitNode()to allocate space to the node
  3. In the main function,Declare n1, n2, but only initialize n1 (allocate space for n1). Because there is no space allocated for n2, an EXC_BAD_ACCESSerror
typedef struct{
    
    
    struct Node *next;
}Node, *NodeHead;

void InitNode(NodeHead *NH){
    
    
    *NH = (Node *)malloc(sizeof(Node));
    (*NH)->next = NULL;
}

void main(){
    
    
    Node *n1, *n2;
    InitNode(&n1);
    n1->next = n2;
    n2->next = n1;
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43728138/article/details/123478855