Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtol reusing param

Tags:

c

pointers

strtol

This code seems to work as expected, populates an array of numbers using a single pointer

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

int main(void)
{
    int arr[4], count = 0, i;
    char *p, s[32] = "  \t  10,  15  \n  ,20,   25  , ";

    p = s;
    do {
        arr[count++] = (int)strtol(p, &p, 10);
        while (isspace(*p) || *p == ',') p++;
    } while (*p);
    for (i = 0; i < count; i++) {
        printf("%d\n", arr[i]);
    }
    return 0;
}

My question is:

It is valid to use p as param1 (source) and &p as param 2 (address of the first invalid character) in strtol?

like image 374
David Ranieri Avatar asked Dec 19 '12 11:12

David Ranieri


2 Answers

Yes, it is safe. The first argument is passed by value, so strtol has a local copy that isn't affected by changes written to the second parameter.

like image 58
Klas Lindbäck Avatar answered Sep 21 '22 12:09

Klas Lindbäck


Yes it is safe.

Please refer to http://en.cppreference.com/w/cpp/string/byte/strtol for complete usage reference. Line 11 of the example illustrates a call using the same variable for the 1st and 2nd parameters.

like image 26
Naresh Avatar answered Sep 22 '22 12:09

Naresh