1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
/**
* util_libc_example - Example program for util_libc
*
* Copyright IBM Corp. 2016, 2017
*
* s390-tools is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
//! [code]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib/util_libc.h"
#include "lib/util_panic.h"
#define EXAMPLE_WORD " /sys/devices/system/cpu "
/*
* Demonstrate that out of memory is automatically handled via panic()
*/
int main(void)
{
unsigned long ulong_max = (unsigned long)-1;
void *ptr;
char *zeroes, *str;
char buffer[sizeof(EXAMPLE_WORD)];
strcat(buffer, EXAMPLE_WORD);
fprintf(stderr, "Try to remove leading and trailing spaces from "
"\"%s\"\nresult = \"%s\"\n", EXAMPLE_WORD,
util_strstrip(buffer));
/* Use util_strcat_realloc() for string concatenation */
fprintf(stderr, "Try to concatenate \"Hello\", \", \" and \"world!\": ");
str = util_strdup("Hello");
str = util_strcat_realloc(str, ", ");
str = util_strcat_realloc(str, "world!");
fprintf(stderr, "result = \"%s\"\n", str);
free(str);
/* Use util_concatf() for string concatenation */
fprintf(stderr, "Try to concatenate \"list\" plus comma-separated list of numbers 1 to 3: ");
str = NULL;
util_concatf(&str, "list:");
for (int i = 1; i <= 3; i++)
util_concatf(&str, "%s%d", (i > 1 ? "," : ""), i);
fprintf(stderr, "result = %s\n", str); /* list:part1,part2,part3 */
/* One byte allocation should work */
fprintf(stderr, "Try to allocate 1 byte: ");
ptr = util_malloc(1);
fprintf(stderr, "done\n");
/* One byte zeroed-allocation should work */
fprintf(stderr, "Try to allocate 1 byte initialized with zeroes: ");
zeroes = util_zalloc(1);
fprintf(stderr, "done\n");
util_assert(*zeroes == 0, "Garbage found in zero initialized memory\n");
/* The next allocation will probably fail */
fprintf(stderr, "Try to allocate %lu bytes:\n", ulong_max);
ptr = util_malloc(ulong_max);
fprintf(stderr, "You should not see me (ptr=%p)!\n", ptr);
return EXIT_FAILURE;
}
//! [code]
|