Skip to content

c - 3.1.1 Noncompliant Code Example (Differing Storage Durations) #21

@nixawk

Description

@nixawk

3.1.1 Noncompliant Code Example (Differing Storage Durations)

In this noncompliant code example, the address of the variable c_str with automatic storage du- ration is assigned to the variable p, which has static storage duration. The assignment itself is valid, but it is invalid for c_str to go out of scope while p holds its address, as happens at the end of dont_do_this().

#include <stdio.h>

const char *p;
void dont_do_this(void) {
    const char c_str[] = "This will change";
    p = c_str; /* Dangerous */
} 

void innocuous(void) {
     printf("%s\n", p);
}

int main(void) {
    dont_do_this();
    innocuous();
    return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions