'Address passed by reference changes after function completes [duplicate]
The task is to read comma separated values in a dynamically allocated array of structs. The reading part works well, but after completion of readcsv() the reference to *addr changes address from 0x55555555a6e0 to 0x1000. Not exactly what I'm looking for since I'll have to sort and print this array afterwards. How do I prevent this from happening? Have I overlooked something in terms of scope?
#include <stdio.h>
#include <stdlib.h>
#define LEN 20
struct address {
char *fname;
char *lname;
long postcode;
char *city;
};
typedef struct address ADR;
int addr_count(FILE *file) {
fseek(file, 0L, SEEK_END);
long file_size = ftell(file);
fseek(file, 0L, SEEK_SET);
char *buff = malloc(file_size);
int c = 0;
while(!feof(file)) {
size_t res = fread(buff, 1, file_size, file);
for(int i = 0; i < res; i++) {
if (buff[i] == '\n') {
c++;
}
}
}
fseek(file, 0L, SEEK_SET);
free(buff);
return c;
}
int readcsv(const char *filename, ADR *addr, int *naddr) {
FILE *file = fopen(filename, "r");
if(file == NULL) {
printf("Error: couldn't read file\n");
return -1;
}
*naddr = addr_count(file);
addr = malloc(sizeof(ADR) * (*naddr));
if(addr == NULL) {
printf("Error: out of memory.\n");
return -1;
}
ADR *start = addr;
fscanf(file, "%*[^\n]\n");
for(int i = 0; i < *naddr; i++) {
addr->fname = malloc(sizeof(char) * LEN);
addr->lname = malloc(sizeof(char) * LEN);
addr->city = malloc(sizeof(char) * LEN);
fscanf(file, "%[^;];%[^;];%ld;%s\n", addr->fname, addr->lname, &addr->postcode, addr->city);
addr++;
}
addr = start;
fclose(file);
return 0;
}
int main() {
ADR *addr;
int naddr;
readcsv("addresses.csv", addr, &naddr);
free(addr);
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
