0

The below C program compiles and runs just fine on GCC 4.9 with -std=c99 with just one warning(warning: assignment makes pointer from integer without a cast) when the strdup is called.

On GCC 6 and above, the same code compiles fine but generates segmentation fault when compiled with -std=c99

Thanks, Dave

#include <stdio.h>
#include <string.h>

typedef enum {
    POOL_ACCOUNTING
} pool_name_e;
typedef struct pool_attributes {
    int     pool_size;
    char   *conn_string;
} pool_attributes_t;

typedef struct connection {
    int                 conn_index;
    pool_name_e         pool_name;
    pool_attributes_t  *pool_attributes;
} connection_t;

typedef struct conn_pool {
    pool_attributes_t    pool_attributes;
} conn_pool_t;

struct {
   conn_pool_t  Accounting;
   conn_pool_t  Support;
} manager;

int main( ) {

    char *value="server=test.local user=test";
    manager.Accounting.pool_attributes.conn_string=strdup(value);
    printf("%s\n",manager.Accounting.pool_attributes.conn_string);
    return 0;
}
cigien
  • 57,834
  • 11
  • 73
  • 112
  • 1
    I don't think `strdup` exists in c99. Did you also get `error: implicit declaration of function ‘strdup’` by chance? – ggorlen Nov 09 '20 at 02:26
  • 1
    Does this answer your question? [C strndup implicit declaration](https://stackoverflow.com/questions/46013382/c-strndup-implicit-declaration) – ggorlen Nov 09 '20 at 02:27
  • @ggorlen, the strdup does not return null just an invalid pointer – Dave Greeko Nov 09 '20 at 02:37
  • 4
    @DaveGreeko When `sizeof(char *) > sizeof(int)` (such as for example in a 64-bit compile) an explicit declaration of `strdup` is required in order to avoid pointer truncation. Add `-D_POSIX_C_SOURCE=200809L`, or replace `-std=c99` with `-std=gnu99`. – dxiv Nov 09 '20 at 03:09
  • 1
    For future reference, "[operation] makes pointer from integer without a cast" is a near-certain indication of a bug--either a missing declaration as here, or a variable given the wrong type. – zwol Nov 09 '20 at 03:14

0 Answers0