C Programming: Pointers and Structures Quiz
45 Questions
3 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What is a key characteristic of a void * pointer in C?

  • It cannot be assigned to other pointer types.
  • It can store any pointer type. (correct)
  • It can only point to integer types.
  • It requires explicit type casting for assignment.
  • What happens when attempting to dereference a void * pointer?

  • It converts the void * pointer to an integer.
  • It yields the address of the pointed location.
  • It retrieves the value at the pointed address.
  • It results in an error. (correct)
  • Which of the following pointer assignments is legally permissible?

  • Assigning an int * pointer to a double * pointer.
  • Assigning an int * pointer to an int variable.
  • Assigning a void * pointer directly to a char * pointer.
  • Assigning a double * pointer to a void * pointer. (correct)
  • Why can assignments between void * pointers and other pointer types be dangerous?

    <p>They may result in runtime errors when dereferenced.</p> Signup and view all the answers

    What is the primary purpose of the C standard allocator?

    <p>To manage memory allocation from the system.</p> Signup and view all the answers

    What operator can be used to determine the size in bytes of a variable or type?

    <p>sizeof</p> Signup and view all the answers

    Which statement is true regarding structure values?

    <p>Their address can be taken with &amp;.</p> Signup and view all the answers

    What is a limitation of the sizeof operator when used with arrays?

    <p>It is only reliable for arrays declared within the current scope.</p> Signup and view all the answers

    What does the 'next' member in the struct IntList represent?

    <p>A pointer to another struct IntList.</p> Signup and view all the answers

    What does a void * type indicate in C programming?

    <p>A pointer of unspecified type.</p> Signup and view all the answers

    What is the correct way to declare a variable of type struct IntList?

    <p>struct IntList varname;</p> Signup and view all the answers

    How do you access the value member of a structure pointer using the pointer variable?

    <p>(*pointer).value;</p> Signup and view all the answers

    Which member access operator is used with structure pointers?

    <p>-&gt;</p> Signup and view all the answers

    What is the purpose of the '->' operator in relation to structure pointers?

    <p>It simplifies access to structure members.</p> Signup and view all the answers

    Which of the following statements regarding structures is false?

    <p>You can directly use the assignment operator with structure pointers.</p> Signup and view all the answers

    What will happen if you do not include a semicolon at the end of a structure declaration?

    <p>The program will not compile.</p> Signup and view all the answers

    What would the expression sizeof(matrix) yield in the context of the provided function?

    <p>The size of the pointer type.</p> Signup and view all the answers

    Which of the following is not a member of the struct ComplexList?

    <p>struct ComplexList *previous;</p> Signup and view all the answers

    Which operation is not legal on structures?

    <p>Adding a structure to another structure.</p> Signup and view all the answers

    How would you initialize the next member of a struct IntList instance to NULL?

    <p>list-&gt;next = NULL;</p> Signup and view all the answers

    The syntax 'struct IntList node = { 7, NULL };' performs what action?

    <p>Creates an instance of struct IntList with initial values.</p> Signup and view all the answers

    What is the purpose of structures in C programming?

    <p>To aggregate multiple data items into a single value.</p> Signup and view all the answers

    What indicates that memory allocation in C is manual?

    <p>The programmer must manage memory allocation and deallocation.</p> Signup and view all the answers

    Which type of structure can form linked lists in C?

    <p>Self-referential structures.</p> Signup and view all the answers

    How does C handle complex data whose size may not be known at compile time?

    <p>Through manual memory allocation.</p> Signup and view all the answers

    What are members of a struct in C?

    <p>Data items that make up the struct.</p> Signup and view all the answers

    What is a potential downside of manual memory allocation in C?

    <p>It may lead to memory leaks if not managed properly.</p> Signup and view all the answers

    What does the term 'self-referential structure' mean in C?

    <p>A structure that can contain pointers to itself.</p> Signup and view all the answers

    What is the main role of the C library regarding memory allocation?

    <p>It provides functions for dynamic memory management.</p> Signup and view all the answers

    What does the function malloc() return?

    <p>A void pointer to a block of allocated memory</p> Signup and view all the answers

    What is the main difference between malloc() and calloc()?

    <p>calloc() allocates memory for arrays and initializes memory to zero</p> Signup and view all the answers

    Which of the following is true regarding the size information of a pointer?

    <p>You need additional information to determine the size of memory a pointer points to</p> Signup and view all the answers

    What will the next pointer in the allocated structure head be set to when using calloc()?

    <p>NULL</p> Signup and view all the answers

    How is memory for an array of 10 integers allocated using malloc()?

    <p>malloc(10 * sizeof(int))</p> Signup and view all the answers

    When should you use calloc() instead of malloc()?

    <p>When you need initialized memory for all bytes</p> Signup and view all the answers

    Which statement correctly describes how malloc() and calloc() handle memory allocation?

    <p>Both functions return the same type of pointer without initializing memory</p> Signup and view all the answers

    In the context of memory allocation, which of the following statements is correct?

    <p>The size of the allocation can often be derived from related variables or functions</p> Signup and view all the answers

    What function is used in C to free allocated memory?

    <p>free()</p> Signup and view all the answers

    What is the result of a failed memory allocation in C?

    <p>NULL is returned.</p> Signup and view all the answers

    What does the term 'use-after-free' refer to?

    <p>Using a pointer after it has been freed.</p> Signup and view all the answers

    How can setting freed pointer variables to NULL help prevent errors?

    <p>It prevents use-after-free errors.</p> Signup and view all the answers

    Why is out-of-bounds access common in heap allocations?

    <p>Because heap allocations do not have a defined size.</p> Signup and view all the answers

    What should you do if you try to allocate a large amount of memory but it fails?

    <p>Adjust the allocation size and try again.</p> Signup and view all the answers

    Which of the following best describes the proper use of the free() function?

    <p>It should only be called on pointers that were allocated with malloc().</p> Signup and view all the answers

    What is a likely consequence of using a pointer after it has been freed?

    <p>The freed memory may be reused, leading to data corruption.</p> Signup and view all the answers

    Study Notes

    Course Information

    • Course title: Systems Programming
    • Course code: CSE 220
    • Instructors: Ethan Blanton, Carl Alphonce, & Eric Mikida
    • Department: Computer Science and Engineering
    • University: University at Buffalo

    Effective Questions

    • For programming questions, ask:
      • What did you do?
      • What did you expect to happen?
      • What actually happened?
      • How are they different?
    • When asking questions, provide context, steps taken, expected outcome and observed outcome

    Building Complex Applications

    • Building more complex applications requires:
      • Data structures, including self-referential structures
      • Allocation of memory at program run time
    • Structures are provided by the C language
    • Memory allocation is provided by the C library

    Structures

    • A C struct aggregates multiple data items into one value.
    • These items are called members.
    • The aggregate is a new (struct) type.
    • Members of a structure are stored together.
    • Self-referential structures can form linked lists, etc.

    Memory Allocation

    • The amount of memory used by complex data may not be known at compile time.
    • Solving this requires memory allocation.
    • Self-referential structures (like lists) are normally allocated.
    • Allocation and release of memory in C is manual.
    • This makes C memory efficient, but also prone to leaks.

    The C Struct

    • A struct is a compound data type consisting of one or more other types.
    • Example: struct IntList { int value; struct IntList *next; };
    • This struct contains an integer and a pointer.
    • value and next are called members of the structure.
    • Any variable of type struct IntList contains both of these members.

    Declaring and Using Structures

    • Syntax for structure declaration:
      • struct StructureTypeName { // Members in structure // Each member has a type and a name } varname;
    • Instance of structure can be created where structure is declared, or using the typename later
      • struct StructureTypeName varname;

    Accessing Structure Members

    • The . operator is used to access structure members
    • Example: struct IntList node = { 7, NULL }; node.value = 3;
    • Any member of a structure can be accessed with the . operator.
    • Example: complexlist.complex.real = 0;

    Structure Pointers

    • The . operator is cumbersome for structure pointers: (*list).next = NULL;
    • The -> operator is syntactic sugar for (*).: list->next = NULL;
    • The -> operator can be used to access any member of a structure via a pointer to the structure type.

    Operations on Structures

    • Structure value:
      • Can have its address taken with &
      • Can be copied with =
      • Can be used to access a member with .
    • Structure pointer:
      • Can do all the things any pointer can do
      • Can be used to access a member with ->

    The sizeof operator

    • There are several operators used to help with reflection in C.
    • sizeof operator returns the size (in bytes) of its operand.
    • Operand can be:
      • A variable
      • An expression that is "like" a variable
      • A type
    • Expressions "like" variable include members of structures.

    Looking at sizeof

    • sizeof arrays is not reliable.
    • Only arrays declared within the current scope will be correct.

    The void* type

    • The type void* is used to indicate a pointer of unknown type.
    • void* variable can store any pointer type.
    • Type checks are mostly bypassed when assigning to/from void*.
    • Any attempt to dereference a void* pointer is an error.

    Pointer Assignments

    • Pointers in C are typed.
      • Example: int i; double d; int *pi = &i; double *pd = &d;
    • void* can be used to assign integer pointers to double pointers, but this is dangerous as it bypasses type safety.

    The Standard Allocator

    • The C library contains a standard allocator.
    • With this allocator you can request memory from the system.
    • Allocated memory is identified by its address.

    Requesting Memory

    • malloc(size_t size): returns a void pointer to usable memory
    • calloc(size_t nmemb, size_t size): returns a void pointer to usable memory with all bytes set to zero

    Allocation Sizes

    • The size of memory allocated with malloc or calloc is not obvious but it's at least as much as the user requested.
    • typically the size of allocations can be derived from:
      • variables or arguments.
      • members in a struct
      • knowledge of the data (like string length strlen()

    Allocating a Structure

    • Example: struct IntList *get_list_pointer() { struct IntList *head = calloc(1, sizeof(struct IntList)); return head; }

    Allocating an Array

    • malloc(10* sizeof(int)): Allocates array of 10 integers.
    • calloc(10,sizeof(int)): Allocates array of 10 integers and sets all bytes to 0.

    Freeing Memory

    • C has no garbage collector.
    • The programmer is responsible for freeing memory after use.
    • Use the free() function: void free(void *ptr)
    • Free accepts pointers allocated with malloc(), calloc(), or realloc().
    • Once a pointer is freed, it should not be used again.

    Failed Allocations

    • Allocations can fail.
    • If allocation fails (malloc or calloc), the function returns NULL.
    • Modern machines return NULL for unreasonable allocations (e.g., 2 GB when you meant 2 KB).
    • Failed allocations can be normal on smaller systems.

    Use-after-free

    • A common error is use-after-free.
    • Occurs when a freed pointer is used after it's freed, potentially leading to incorrect results or program crashes.

    Out-of-bounds access

    • Heap allocations don't have obvious size.
    • This makes out-of-bounds access easy.
    • The compiler won't typically catch an attempt to access memory outside the allocated space.

    Summary

    • Structs are collections of values.
    • Structs can be self-referential.
    • The C standard library contains a flexible allocator.
    • Standard allocator allocations are sized by the programmer.
    • C doesn't have a way to query the size of an allocation

    References

    • Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Second Edition. Chapter 2: 2.7; Chapter 6: Intro, 6.1–6.7. Prentice Hall, 1988.
    • Linux man-pages project. man 3 malloc.

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    Description

    Test your knowledge of pointers and structures in C programming with this quiz. Covering key concepts such as void pointers, memory allocation, and the use of operators, this quiz will challenge your understanding of these fundamental programming topics. Perfect for students and developers looking to refresh their skills.

    More Like This

    Use Quizgecko on...
    Browser
    Browser