How to use Strings (way to quick briefing)

Slides:



Advertisements
Similar presentations
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Advertisements

C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
Strings.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.
. Plab – Tirgul 2 Const, C Strings. Pointers int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; ijx 1.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
University of Washington CSE 351 : The Hardware/Software Interface Section 5 Structs as parameters, buffer overflows, and lab 3.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
Chapter 6 Buffer Overflow. Buffer Overflow occurs when the program overwrites data outside the bounds of allocated memory It was one of the first exploited.
Natalia Yastrebova What is Coverity? Each developer should answer to some very simple, yet difficult to answer questions: How do I find new.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Java Basics.  To checkout, use: svn co scb07f12/UTORid  Before starting coding always use: svn update.
Overflow Examples 01/13/2012. ACKNOWLEDGEMENTS These slides where compiled from the Malware and Software Vulnerabilities class taught by Dr Cliff Zou.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
More C++ Features True object initialisation
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
C Lab 1 Introduction to C. Basics of C Developed by Dennis Ritchie in the 1970s. Maps very easily to machine instructions. Even allows inline assembly!
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
CO4301 – Advanced Games Development Week 1 Introduction
Dynamic Allocation in C
Pointers and Dynamic Arrays
Exceptions David Rabinowitz.
Strings CSCI 112: Programming in C.
5.13 Recursion Recursive functions Functions that call themselves
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Day 03 Introduction to C.
Motivation and Overview
Pointers and Memory Overview
Java Review: Reference Types
LinkedList Class.
This pointer, Dynamic memory allocation, Constructors and Destructor
The Bag and Sequence Classes with Linked Lists
CMSC 202 Lesson 21 Exceptions II.
Pointers and Linked Lists
CSCI206 - Computer Organization & Programming
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
CS212: Object Oriented Analysis and Design
C++ STRINGS string is part of the Standard C++ Library
Pointers, Dynamic Data, and Reference Types
Initialization List.
Pointers and Pointer-Based Strings
Week 9 – Lesson 1 Arrays – Character Strings
Dynamic Memory Allocation
Exceptions 2 CMSC 202.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Variables Title slide variables.
Dynamic Allocation in C
TUTORIAL 8 CS 137 F18 November 5th.
Passing Arguments and The Big 5
Passing Arguments and The Big 5
Destructors, Copy Constructors & Copy Assignment Operators
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
Destructors, Copy Constructors & Copy Assignment Operators
SPL – PS3 C++ Classes.
SPL – PS2 C++ Memory Handling.
Workshop 1++: A bit of C++
CSE 303 Concepts and Tools for Software Development
Introduction to C CS 3410.
Presentation transcript:

How to use Strings (way to quick briefing) Jason Kenny

Overview Current issues std::string_view and std::string C interfaces What about all these other string objects?

What are the current problems? Current logic has unclear ownership rules. Do you delete or not? Difficult to return new strings without leaking small about of memory We often make un-needed copies and memory allocations We are doing extra strlen() calls when we don't have to

Examples: Core issue char* function(...) char *v1 = function(); Do we need to delete v1? class obj {   char* method(...) } Obj myobj; ... char *v2 = myobj.method(); Do we need to delete v2?

std::string Owns memory Can reserve memory to avoid memory allocation Never leaks Can reserve memory to avoid memory allocation Via reserve() Assignments will copy data in to string This does not always mean we have to alloc Small strings don't need to alloc any memory Larger strings are based on capacity() of the string Always know the size()\length() in constant time On function returns move symantecs allow memory to move/transfer between objects. Ends with a Null terminator for C interface compatibility.

std::string_view Does not own memory Points to a range of original string Always know the size()\length() in constant time String is immutable ( unless you cheat with const_cast) Range pointed to is mutable.

Pass by reference Do: Function (std::string const &str) {} Function (std::string &str) {} Function (ts::string_view &sv) {} Don’t do: Function (std::string str) {} Avoid: Function (ts::string_view str) {}

Return values OK: std::string const& Myclass::foo() Better: ts::string_view Myclass::foo()

Making temporary string Existing code: char * layout_relative(const char *root, const char *file) { char path[PATH_NAME_MAX]; ... return ats_strdup(path); // copy string (malloc and string copy. May Leak) } New Way std::string layout_relative(ts:string_view const &root, char ts:string_view const &file) std::string ret(path); // copy string return path; //no leaking!!

Interface with C interfaces ( wants char*) Prefer C interfaces with pointer and length as input ie : c_func(char *, size_t length) With std::string: c_func(s.c_str(),s.length()); With std::string_view: c_func(s.data(),s.length());

Interface with C interfaces - Continue Sometimes we have C API that only take char* and no size. Assume NULL terminator With std::string: c_func(s.c_str()); // Has NULL terminator

Interface with C interfaces - Continue WARNING!! std::string_view: c_func(sv.data()); // Make not have NULL terminator Make it safe: (unless you know for sure the object is at the end) std::string tmp(sv.data(),sv.length()); c_func(tmp.c_str()); Can also say: ( can blow the stack, but avoids an possible alloc) char tmp[sv.length+1]; sv.copy(tmp,sv.length());

Conclusion Use std::string: Use std::string_view To be the “owner” of the string data For mutable operations Use std::string_view In case in which we need a immutable copy. Pass substrings Clear ownership intent in the API This will prevent memory leaks by mistake Will be as fast as char* ( no extra copies, or memory allocs) No need to call strlen() everywhere